複製、刪除、移動檔案、擷取檔案的版本資訊、變更檔屬性,刪除唯讀檔案

來源:互聯網
上載者:User

複製檔案:
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()+"行資料");
}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.