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

.NET 開發實用技巧大全

     編輯:關於.NET

一、.NET Framework 基礎操作

1. 取得系統特殊資料夾路徑

使用 Environment.GetFolderPath 方法搭配 Environment.SpecialFolder 列舉:

string myDocs = Environment.GetFolderPath(Environment.SpecialFolder.Personal);

2. 取得正在執行的 EXE 路徑

兩種常用方式:

// 方式 1:Windows Forms 應用
string path1 = Application.ExecutablePath;

// 方式 2:通用做法
string path2 = System.Reflection.Assembly.GetExecutingAssembly().Location;

3. 偵測作業系統版本

OperatingSystem os = Environment.OSVersion;
MessageBox.Show(os.Version.ToString());  // 版本號
MessageBox.Show(os.Platform.ToString()); // 平台類型

4. 從完整路徑解析檔名與副檔名

string fileName = System.IO.Path.GetFileName(fullPath);           // 含副檔名
string fileNameOnly = System.IO.Path.GetFileNameWithoutExtension(fullPath); // 不含副檔名
string extension = System.IO.Path.GetExtension(fullPath);         // 僅副檔名

5. 取得電腦硬體資訊

透過 System.Windows.Forms.SystemInformation 靜態屬性可獲取:當前用戶名、網路連線狀態、顯示器數量、網域名稱、滑鼠按鍵數等。

6. [STAThread] 屬性用途

標示主執行緒採用單執行緒單元 (STA) 模式運行,Windows Forms 應用程式進入點必須加此屬性。

7. 讀取 CSV 檔案

使用 ODBC 連線字串:

string connStr = @"Driver={Microsoft Text Driver (*.txt;*.csv)};Dbq=" + folderPath + @"; Extensions=asc,csv,tab,txt; Persist Security Info=False";
OdbcConnection conn = new OdbcConnection(connStr);
// 後續可用 DataAdapter 存取

8. 取得磁碟空間資訊 (P/Invoke)

public sealed class DriveInfo
{
    [DllImport("kernel32.dll", EntryPoint = "GetDiskFreeSpaceExA")]
    private static extern long GetDiskFreeSpaceEx(string lpDirectoryName,
        out long lpFreeBytesAvailableToCaller,
        out long lpTotalNumberOfBytes,
        out long lpTotalNumberOfFreeBytes);

    public static long GetInfo(string drive, out long available, out long total, out long free)
    {
        return GetDiskFreeSpaceEx(drive, out available, out total, out free);
    }

    public static DriveInfoSystem GetInfo(string drive)
    {
        long result, available, total, free;
        result = GetDiskFreeSpaceEx(drive, out available, out total, out free);
        return new DriveInfoSystem(drive, result, available, total, free);
    }
}

public struct DriveInfoSystem
{
    public readonly string Drive;
    public readonly long Result;
    public readonly long Available;
    public readonly long Total;
    public readonly long Free;
    public DriveInfoSystem(string drive, long result, long available, long total, long free)
    {
        this.Drive = drive; this.Result = result; this.Available = available;
        this.Total = total; this.Free = free;
    }
}

// 使用範例
DriveInfoSystem info = DriveInfo.GetInfo("c:");

9. 不區分大小尋找子字串索引

方法一:轉小寫後比對

string parent = "The Codeproject site is very informative.";
string child = "codeproject";
int index = parent.ToLower().IndexOf(child.ToLower()); // 正確回傳 4

方法二:使用 CompareInfo (更優雅)

using System.Globalization;
CompareInfo cmp = CultureInfo.InvariantCulture.CompareInfo;
int index = cmp.IndexOf(parent, child, CompareOptions.IgnoreCase);

二、物件導向觀念

1. 複製建構函式

避免參考複製,建立全新實例:

public class Student
{
    private string name;
    public Student(string name) { this.name = name; }
    // 複製建構函式
    public Student(Student student) { this.name = student.name; }
    public string Name { get { return name; } set { name = value; } }
}

// 使用
Student s1 = new Student("A");
Student s2 = new Student(s1); // 建立新實例
s1.Name = "B";
Console.WriteLine(s2.Name); // 輸出 "A"

2. 唯讀常數

class Numbers
{
    public readonly int m;        // 實體唯讀欄位
    public static readonly int n; // 靜態唯讀常數
    public Numbers(int x) { m = x; }
    static Numbers() { n = 100; } // 靜態建構函式初始化
}

三、VS.NET IDE 技巧

變更 #region 摺疊區塊顏色

工具 → 選項 → 環境 → 字型及顏色 → 可摺疊文字 進行設定。

四、WinForm 實用設定

1. 隱藏標題列

form1.Text = string.Empty;
form1.ControlBox = false;

2. 禁止在工作列顯示

form1.ShowInTaskbar = false;

3. 啟動預設郵件程式

Web 應用:

<a href="mailto:email@address1.com,email@address2.com?cc=email@address3.com&Subject=Hello&body=Happy New Year">寄信</a>

Windows 應用:

Process proc = new Process();
proc.StartInfo.FileName = @"mailto:email@address1.com?subject=Hello&body=Happy New Year";
proc.Start();

4. 建立類似 MSN 的彈出提示視窗

取得工作區寬高 Screen.GetWorkingArea(this).Width/Height,配合 Timer 動態調整視窗位置。

五、Button 控制項技巧

  • 預設按鈕 (Enter 鍵觸發):form1.AcceptButton = button1;
  • 取消按鈕 (Esc 鍵觸發):form1.CancelButton = buttonC;
  • 程式觸發 Click 事件:Button1.PerformClick();

六、ComboBox 填充字體清單

comboBox1.Items.AddRange(FontFamily.Families);

七、TextBox 進階控制

  • 停用預設右鍵選單:textBox1.ContextMenu = new ContextMenu();
  • 焦點移至文字末端:textBox1.SelectionStart = textBox1.Text.Length;
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved