溫馨提示×

winform怎么讀取本地文件

小億
256
2023-12-07 19:55:27

在WinForms中,可以使用OpenFileDialog對話框來讀取本地文件。以下是一個(gè)簡單的示例:

private void ReadFileButton_Click(object sender, EventArgs e)
{
    OpenFileDialog openFileDialog = new OpenFileDialog();
    
    if (openFileDialog.ShowDialog() == DialogResult.OK)
    {
        string filePath = openFileDialog.FileName;
        
        // 使用適當(dāng)?shù)姆绞阶x取文件內(nèi)容
        // 例如,使用StreamReader來讀取文本文件的內(nèi)容
        using (StreamReader reader = new StreamReader(filePath))
        {
            string fileContent = reader.ReadToEnd();
            
            // 將文件內(nèi)容顯示在文本框中
            fileContentTextBox.Text = fileContent;
        }
    }
}

在上面的示例中,當(dāng)用戶點(diǎn)擊一個(gè)按鈕(例如ReadFileButton)時(shí),會彈出一個(gè)OpenFileDialog對話框,用戶可以選擇要讀取的本地文件。一旦用戶選擇了文件并點(diǎn)擊了“確定”按鈕,就可以獲取選中文件的路徑(openFileDialog.FileName),然后使用適當(dāng)?shù)姆椒ǎɡ缡褂?code>StreamReader)讀取文件的內(nèi)容。

0