複製檔案:
FileInfo fiMyfile = new FileInfo(@"C:\123\456.txt");
if(fiMyfile.Exists)
{
fiMyfile.CopyTo(@"D:\123\456.txt", true);
}
刪除檔案:
FileInfo fiMyfile = new FileInfo(@"C:\123\456.txt");
if(fiMyfile.Exists)
{
fiMyfile.Delete();
}
//拷貝檔案
File.Copy(OrignFile,NewFile);
//刪除檔案
File.Delete(delFile);
//移動檔案
File.Move(OrignFile,NewFile);
if(File.Exists(OrignFile))
{
FileInfo fi = new FileInfo(NewFile);
DateTime Ctime = fi.CreationTime;
}
//====================================================================
擷取檔案的版本資訊:
FileVersionInfo myFileVersionInfo1 = FileVersionInfo.GetVersionInfo("D:\\TEST.DLL"); textBox1.Text="版本號碼: " + myFileVersionInfo1.FileVersion; |
變更檔屬性,刪除唯讀檔案:
下例欲將E:\test.txt檔案拷貝至D:\tmp\test.txt,但D:\tmp\test.txt已經存在。
//File.Copy(sourceFile,destinationFile,true); 用來拷貝檔案 //當destinationFile已經存在時,無法將檔案file1拷貝到目標檔案, //因此先刪除destination檔案,File.Delete()方法不能刪除唯讀檔案, //因此,如果檔案屬性為唯讀(Attributes屬性中會包含有"ReadOnly"), //先把檔案屬性重設為Normal,然後再刪除: string file1="E:\\test.txt"; string destinationFile="d:\\tmp\\test.txt"; if(File.Exists(destinationFile)) { FileInfo fi=new FileInfo(destinationFile); if(fi.Attributes.ToString().IndexOf("ReadOnly")!=-1) fi.Attributes=FileAttributes.Normal; File.Delete(destinationFile); } File.Copy(file1,destinationFile,true); |
判斷檔案是否存在:File.Exists(string filePath)
判斷目錄是否存在:Directory.Exists("D:\\LastestVersion")
按行讀取檔案:
int fileCount=0; // Open the file just specified such that no one else can use it. StreamReader sr = new StreamReader(textBox1.Text.Trim()); while(sr.Peek() > -1)//StreamReader.Peek()返回下一個可用字元,但不使用它 { listBox1.Items.Add(sr.ReadLine()); fileCount++; } sr.Close(); |
按行寫入檔案:
StreamWriter sw = new StreamWriter("D:\\result.txt"); for(int i=0;i<10;i++) { sw.WriteLine("這是第"+i.ToString()+"行資料"); } |