擷取檔案的版本資訊:
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;