c#程式碼片段——檔案操作部分

來源:互聯網
上載者:User
擷取檔案的版本資訊:

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);

  C#中字串的格式化及轉換成數值的方法

  字串轉換成數字,比如"1234"轉換成數字1234:

string str="1234";
int i=Convert.ToInt32(str); 

  格式化字串,向長度小於30的字串末尾添加特定字元,補足n個字元,使用String類的PadRight(int,char)方法:

String str="1234";
str=str.PadRight(30,' ') //向長度小於30的字串末尾添加空格,補足30個字元

  按行讀寫檔案

  判斷檔案是否存在: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{
 sw.WriteLine("這是第"+i.ToString()+"行資料");
}

  檔案目錄對話方塊的使用

  檔案對話方塊即過濾條件的使用:

string resultFile="";
OpenFileDialog openFileDialog1 = new OpenFileDialog();
openFileDialog1.InitialDirectory = "D:\\Patch" ;
openFileDialog1.Filter = "All files (*.*)|*.*|txt files (*.txt)|*.txt" ;
openFileDialog1.FilterIndex = 2 ;
openFileDialog1.RestoreDirectory = true ;
if(openFileDialog1.ShowDialog() == DialogResult.OK)
resultFile=openFileDialog1.FileName; 

  目錄對話方塊的使用:

string resultFolder="";
FolderBrowserDialog openFolderDialog1=new FolderBrowserDialog();
openFolderDialog1.RootFolder=Environment.SpecialFolder.MyComputer;
if(openFolderDialog1.ShowDialog()==DialogResult.OK)
resultFolder=openFolderDialog1.SelectedPath; 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.