首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> .NET 網頁程式設計 >> C# >> 關於C#

C# 程式設計實用技巧大全

     編輯:關於C#

一、取得檔案版本資訊

利用 FileVersionInfo 類別可輕鬆讀取組件或原生 DLL/EXE 的版本號:

FileVersionInfo info = FileVersionInfo.GetVersionInfo(@"D:\TEST.DLL");
textBox1.Text = $"版本號: {info.FileVersion}";

二、變更檔案屬性並刪除唯讀檔案

File.Copy 覆寫時若目標檔案為唯讀會失敗,需先移除唯讀屬性:

string src = @"E:\test.txt";
string dest = @"d:\tmp\test.txt";

if (File.Exists(dest))
{
    FileInfo fi = new FileInfo(dest);
    if ((fi.Attributes & FileAttributes.ReadOnly) == FileAttributes.ReadOnly)
        fi.Attributes = FileAttributes.Normal; // 移除唯讀
    File.Delete(dest);
}
File.Copy(src, dest, true);

三、字串格式化與數值轉換

1. 字串轉數值

string str = "1234";
int val = Convert.ToInt32(str); // 或 int.Parse(str)

2. 字串靠右補齊指定長度

string s = "1234";
s = s.PadRight(30, ' '); // 尾部補空白至 30 字元

四、檔案逐行讀寫

判斷檔案/目錄是否存在

bool fileExists = File.Exists(path);
bool dirExists = Directory.Exists(@"D:\LastestVersion");

逐行讀取文字檔

int count = 0;
using (StreamReader sr = new StreamReader(textBox1.Text.Trim()))
{
    while (sr.Peek() > -1)
    {
        listBox1.Items.Add(sr.ReadLine());
        count++;
    }
}

逐行寫入文字檔

using (StreamWriter sw = new StreamWriter(@"D:\result.txt"))
{
    for (int i = 0; i < 10; i++)
        sw.WriteLine($"這是第{i}行資料");
}

五、檔案與目錄對話框應用

開啟檔案對話框(含過濾器)

string file = "";
using (OpenFileDialog dlg = new OpenFileDialog())
{
    dlg.InitialDirectory = @"D:\Patch";
    dlg.Filter = "所有檔案 (*.*)|*.*|文字檔 (*.txt)|*.txt";
    dlg.FilterIndex = 2;
    dlg.RestoreDirectory = true;
    if (dlg.ShowDialog() == DialogResult.OK)
        file = dlg.FileName;
}

選擇資料夾對話框

string folder = "";
using (FolderBrowserDialog dlg = new FolderBrowserDialog())
{
    dlg.RootFolder = Environment.SpecialFolder.MyComputer;
    if (dlg.ShowDialog() == DialogResult.OK)
        folder = dlg.SelectedPath;
}
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved