- 向文件中追加文本 File.AppendText FileInfo.AppendText
- 重命名或移动文件 File.Move FileInfo.MoveTo
- 删除文件 File.Delete FileInfo.Delete
- 复制文件 File.Copy FileInfo.CopyTo
- 获取文件大小 FileInfo.Length
- 获取文件属性 File.GetAttributes
- 设置文件属性 File.SetAttributes
- 确定文件是否存在 File.Exists
- 读取二进制文件 对刚创建的数据文件进行读取和写入
- 写入二进制文件 对刚创建的数据文件进行读取和写入
- 检索文件扩展名 Path.GetExtension
- 检索文件的完全限定路径 Path.GetFullPath
- 检索路径中的文件名和扩展名 Path.GetFileName
- 更改文件扩展名 Path.ChangeExtension
- 目录操作
- System.IO 类
- 目录操作
- string[] drives = Directory.GetLogicalDrives();
- string path = Directory.GetCurrentDirectory();
- Path.GetFileName(@"c:\dir\file.txt");
- Directory.GetFiles(路径及文件名)
- DirectoryInfo di = new DirectoryInfo(@"f:\MyDir");
- DirectoryInfo di=Directory.CreateDirectory(@"f:\bbs");
- if (di.Exists == false)
- di.Create();
- DirectoryInfo dis = di.CreateSubdirectory("SubDir");
- dis.Delete(true);
- di.Delete(true);
- 文件操作
- Directory.Delete(@"f:\bbs2", true);
- Directory.GetDirectories 方法
- string[] dirs = Directory.GetDirectories(@"f:\", "b*");
- Console.WriteLine("此目录中以b开头的子目录共{0}个!", dirs.Length);
- foreach (string dir in dirs) { Console.WriteLine(dir); }
- Directory.GetFileSystemEntries
- Directory.GetLogicalDrives
- Directory.GetParent
- DirectoryInfo a = Directory.GetParent(path);
- Console.WriteLine(a.FullName);Directory.Move
- Directory.Move(@"f:\bbs\1", @"f:\bbs\2");
-
- Stream
-
- BinaryReader和BinaryWriter
-
- FileStream类通过Seek()方法进行对文件的随机访问,默认为同步
-
- TextReader和TextWriter
-
- StringReader和StringWriter
-
- StreamReader和StreamWriter
-
- BufferedStream 为诸如网络流的其它流添加缓冲的一种流类型.
-
- MemoryStream 无缓冲的流
-
- NetworkStream 互联网络上的流
- Encoding e1 = Encoding.Default;
- Byte[] bytes = e1.GetBytes("中国人民解放军");
- string str = Encoding.GetEncoding("UTF-8").GetString(bytes);
-
-
- using System;
- using System.IO;
- class Test
- {
- string path = @"f:\t.txt";
- public static void Main()
- {
-
- if (!File.Exists(path))
- {
- using (StreamWriter sw = File.CreateText(path))
- {
- sw.WriteLine("Hello");
- }
- }
-
- using (StreamReader sr = File.OpenText(path))
- {
- string s = "";
- while ((s = sr.ReadLine()) != null)
- {
- Console.WriteLine(s);
- }
- }
-
- try
- {
- File.Delete(path);
- File.Copy(path, @"f:\tt.txt");
- }
- catch (Exception e)
- {
- Console.WriteLine("The process failed: {0}", e.ToString());
- }
- }
- }
- private const string name = "Test.data";
- public static void Main(String[] args)
- {
-
- FileStream fs = new FileStream(name, FileMode.CreateNew);
-
- Byte[] info = new UTF8Encoding(true).GetBytes("This is some text in the file.");
-
- fs.Write(info, 0, info.Length);
- w.Close();
- fs.Close();
-
- fs = new FileStream(name, FileMode.Open, FileAccess.Read);
-
- BinaryReader r = new BinaryReader(fs);
- for (int i = 0; i < 11; i++)
- {
- Console.WriteLine(r.ReadInt32());
- }
- w.Close();
- fs.Close();
- }
- C#追加文件
- StreamWriter sw = File.AppendText(Server.MapPath(".")+"\\myText.txt");
- sw.WriteLine("追逐理想");
- sw.WriteLine("kzlll");
- sw.WriteLine(".NET笔记");
- sw.Flush();
- sw.Close();
-
- C#拷贝文件
- string OrignFile,NewFile;
- OrignFile = Server.MapPath(".")+"\\myText.txt";
- NewFile = Server.MapPath(".")+"\\myTextCopy.txt";
- File.Copy(OrignFile,NewFile,true);
-
- C#删除文件
- string delFile = Server.MapPath(".")+"\\myTextCopy.txt";
- File.Delete(delFile);
-
- C#移动文件
- string OrignFile,NewFile;
- OrignFile = Server.MapPath(".")+"\\myText.txt";
- NewFile = Server.MapPath(".")+"\\myTextCopy.txt";
- File.Move(OrignFile,NewFile);
-
- C#创建目录
-
- DirectoryInfo d=Directory.CreateDirectory("c:\\sixAge");
-
- DirectoryInfo d1=d.CreateSubdirectory("sixAge1");
-
- DirectoryInfo d2=d1.CreateSubdirectory("sixAge1_1");
-
- Directory.SetCurrentDirectory("c:\\sixAge");
-
- Directory.CreateDirectory("sixAge2");
-
- Directory.CreateDirectory("sixAge2\\sixAge2_1");
- 递归删除文件夹及文件
- public void DeleteFolder(string dir)
- {
- if (Directory.Exists(dir))
- {
- foreach(string d in Directory.GetFileSystemEntries(dir))
- {
- if(File.Exists(d))
- File.Delete(d);
- else
- DeleteFolder(d);
- }
- Directory.Delete(dir);
- Response.Write(dir+" 文件夹删除成功");
- }
- else
- Response.Write(dir+" 该文件夹不存在");
- }
- protected void Page_Load (Object sender ,EventArgs e)
- {
- string Dir="D:\\gbook\\11";
- DeleteFolder(Dir);
- }
-
- copy文件夹内容
- 实现一个静态方法将指定文件夹下面的所有内容copy到目标文件夹下面,如果目标文件夹为只读属性就会报错。
- 方法1.
- public static void CopyDir(string srcPath,string aimPath)
- {
- try
- {
-
- if(aimPath[aimPath.Length-1] != Path.DirectorySeparatorChar)
- aimPath += Path.DirectorySeparatorChar;
-
- if(!Directory.Exists(aimPath)) Directory.CreateDirectory(aimPath);
-
-
-
- string[] fileList = Directory.GetFileSystemEntries(srcPath);
-
- foreach(string file in fileList)
- {
-
- if(Directory.Exists(file))
- CopyDir(file,aimPath+Path.GetFileName(file));
-
- else
- File.Copy(file,aimPath+Path.GetFileName(file),true);
- }
- }
- catch (Exception e)
- {
- MessageBox.Show (e.ToString());
- }
- }
- 方法2.
- public static void CopyFolder(string strFromPath,string strToPath)
- {
-
- if (!Directory.Exists(strFromPath))
- {
- Directory.CreateDirectory(strFromPath);
- }
-
- string strFolderName = strFromPath.Substring(strFromPath.LastIndexOf("\\") + 1,strFromPath.Length - strFromPath.LastIndexOf("\\") - 1);
-
- if (!Directory.Exists(strToPath + "\\" + strFolderName))
- {
- Directory.CreateDirectory(strToPath + "\\" + strFolderName);
- }
-
- string[] strFiles = Directory.GetFiles(strFromPath);
-
- for(int i = 0;i < strFiles.Length;i++)
- {
-
- string strFileName = strFiles[i].Substring(strFiles[i].LastIndexOf("\\") + 1,strFiles[i].Length - strFiles[i].LastIndexOf("\\") - 1);
-
- File.Copy(strFiles[i],strToPath + "\\" + strFolderName + "\\" + strFileName,true);
- }
-
- DirectoryInfo dirInfo = new DirectoryInfo(strFromPath);
-
- DirectoryInfo[] ZiPath = dirInfo.GetDirectories();
- for (int j = 0;j < ZiPath.Length;j++)
- {
-
- string strZiPath = strFromPath + "\\" + ZiPath[j].ToString();
-
- CopyFolder(strZiPath,strToPath + "\\" + strFolderName);
- }
- }
-
- 删除文件夹内容
- 实现一个静态方法将指定文件夹下面的所有内容Detele,测试的时候要小心操作,删除之后无法恢复。
- public static void DeleteDir(string aimPath)
- {
- try
- {
-
- if(aimPath[aimPath.Length-1] != Path.DirectorySeparatorChar)
- aimPath += Path.DirectorySeparatorChar;
-
-
-
- string[] fileList = Directory.GetFileSystemEntries(aimPath);
-
- foreach(string file in fileList)
- {
-
- if(Directory.Exists(file))
- {
- DeleteDir(aimPath+Path.GetFileName(file));
- }
-
- else
- {
- File.Delete (aimPath+Path.GetFileName(file));
- }
- }
-
- System.IO .Directory .Delete (aimPath,true);
- }
- catch (Exception e)
- {
- MessageBox.Show (e.ToString());
- }
- }
-
- 读取文本文件
- private void ReadFromTxtFile()
- {
- if(filePath.PostedFile.FileName != "")
- {
- txtFilePath =filePath.PostedFile.FileName;
- fileExtName = txtFilePath.Substring(txtFilePath.LastIndexOf(".")+1,3);
-
- if(fileExtName !="txt" && fileExtName != "TXT")
- {
- Response.Write("请选择文本文件");
- }
- else
- {
- StreamReader fileStream = new StreamReader(txtFilePath,Encoding.Default);
- txtContent.Text = fileStream.ReadToEnd();
- fileStream.Close();
- }
- }
- }
-
- 获取文件列表
- 看到动态表的影子,这个应该是从项目里面拷贝出来的。
- private void GetFileList()
- {
- string strCurDir,FileName,FileExt;
-
- long FileSize;
-
- DateTime FileModify;
-
- if(!IsPostBack)
- {
-
- strCurDir = Server.MapPath(".");
- lblCurDir.Text = strCurDir;
- txtCurDir.Text = strCurDir;
- }
- else
- {
- strCurDir = txtCurDir.Text;
- txtCurDir.Text = strCurDir;
- lblCurDir.Text = strCurDir;
- }
- FileInfo fi;
- DirectoryInfo dir;
- TableCell td;
- TableRow tr;
- tr = new TableRow();
-
- td = new TableCell();
- td.Controls.Add(new LiteralControl("文件名"));
- tr.Cells.Add(td);
- td = new TableCell();
- td.Controls.Add(new LiteralControl("文件类型"));
- tr.Cells.Add(td);
- td = new TableCell();
- td.Controls.Add(new LiteralControl("文件大小"));
- tr.Cells.Add(td);
- td = new TableCell();
- td.Controls.Add(new LiteralControl("最后修改时间"));
- tr.Cells.Add(td);
- tableDirInfo.Rows.Add(tr);
-
- DirectoryInfo dirInfo = new DirectoryInfo(txtCurDir.Text);
-
- foreach(FileSystemInfo fsi in dirInfo.GetFileSystemInfos())
- {
- FileName = "";
- FileExt = "";
- FileSize = 0;
-
- if(fsi is FileInfo)
- {
- fi = (FileInfo)fsi;
-
- FileName = fi.Name;
-
- FileExt = fi.Extension;
-
- FileSize = fi.Length;
-
- FileModify = fi.LastWriteTime;
- }
-
- else
- {
- dir = (DirectoryInfo)fsi;
-
- FileName = dir.Name;
-
- FileModify = dir.LastWriteTime;
-
- FileExt = "文件夹";
- }
-
- tr = new TableRow();
- td = new TableCell();
- td.Controls.Add(new LiteralControl(FileName));
- tr.Cells.Add(td);
- td = new TableCell();
- td.Controls.Add(new LiteralControl(FileExt));
- tr.Cells.Add(td);
- td = new TableCell();
- td.Controls.Add(new LiteralControl(FileSize.ToString()+"字节"));
- tr.Cells.Add(td);
- td = new TableCell();
- td.Controls.Add(new LiteralControl(FileModify.ToString("yyyy-mm-dd hh:mm:ss")));
- tr.Cells.Add(td);
- tableDirInfo.Rows.Add(tr);
- }
- }
-
- 读取日志文件
- private void ReadLogFile()
- {
-
- FileStream fs = new FileStream(Server.MapPath("upedFile")+"\\logfile.txt", FileMode.OpenOrCreate, FileAccess.Read);
-
- StringBuilder output = new StringBuilder();
-
- output.Length = 0;
-
- StreamReader read = new StreamReader(fs);
-
- read.BaseStream.Seek(0, SeekOrigin.Begin);
-
- while (read.Peek() > -1)
- {
-
- output.Append(read.ReadLine() + "\n");
- }
-
- read.Close();
-
- return output.ToString();
- }
-
- 写入日志文件
- private void WriteLogFile(string input)
- {
-
- string fname = Server.MapPath("upedFile") + "\\logfile.txt";
-
- FileInfo finfo = new FileInfo(fname);
-
- if ( finfo.Exists && finfo.Length > 2048 )
- {
-
- finfo.Delete();
- }
-
- using(FileStream fs = finfo.OpenWrite())
- {
-
- StreamWriter w = new StreamWriter(fs);
-
- w.BaseStream.Seek(0, SeekOrigin.End);
- w.Write("\nLog Entry : ");
-
- w.Write("{0} {1} \r\n",DateTime.Now.ToLongTimeString(),DateTime.Now.ToLongDateString());
-
- w.Write(input + "\n");
-
- w.Write("------------------------------------\n");
-
- w.Flush();
-
- w.Close();
- }
- }
-
- C#创建HTML文件
- private void CreateHtmlFile()
- {
-
- string[] newContent = new string[5];
- StringBuilder strhtml = new StringBuilder();
- try
- {
-
- using (StreamReader sr = new StreamReader(Server.MapPath("createHTML") + "\\template.html"))
- {
- String oneline;
-
- while ((oneline = sr.ReadLine()) != null)
- {
- strhtml.Append(oneline);
- }
- sr.Close();
- }
- }
- catch(Exception err)
- {
-
- Response.Write(err.ToString());
- }
-
- newContent[0] = txtTitle.Text;
- newContent[1] = "BackColor='#cccfff'";
- newContent[2] = "#ff0000";
- newContent[3] = "100px";
- newContent[4] = txtContent.Text;
-
- try
- {
-
- string fname = Server.MapPath("createHTML") +"\\" + DateTime.Now.ToString("yyyymmddhhmmss") + ".html";
-
- for(int i=0;i < 5;i++)
- {
- strhtml.Replace("$htmlkey["+i+"]",newContent[i]);
- }
-
- FileInfo finfo = new FileInfo(fname);
-
- using(FileStream fs = finfo.OpenWrite())
- {
-
- StreamWriter sw = new StreamWriter(fs,System.Text.Encoding.GetEncoding("GB2312"));
-
- sw.WriteLine(strhtml);
- sw.Flush();
- sw.Close();
- }
-
- hyCreateFile.Text = DateTime.Now.ToString("yyyymmddhhmmss")+".html";
- hyCreateFile.NavigateUrl = "createHTML/"+DateTime.Now.ToString("yyyymmddhhmmss")+".html";
- }
- catch(Exception err)
- {
- Response.Write (err.ToString());
- }
- }
-
- CreateDirectory方法的使用
- using System;
- using System.IO;
- class Test
- {
- public static void Main()
- {
-
- string path = @"c:\MyDir";
- try
- {
-
- if (Directory.Exists(path))
- {
- Console.WriteLine("That path exists already.");
- return;
- }
-
- DirectoryInfo di = Directory.CreateDirectory(path);
- Console.WriteLine("The directory was created successfully at {0}.", Directory.GetCreationTime(path));
-
- di.Delete();
- Console.WriteLine("The directory was deleted successfully.");
- }
- catch (Exception e)
- {
- Console.WriteLine("The process failed: {0}", e.ToString());
- }
- finally {}
- }
- }
posted @
2019-02-10 12:20
cutdragonhit
阅读(
2129)
评论()
编辑
收藏
举报
#foot
{
font-size:8px;
font-color:white;
}