WinFormでローカルファイルをどうやって読み込むのか

WinForms では OpenFileDialog ダイアログを使って、ローカルファイルから読み込みを行うことができます。簡単な例を以下に示します。

private void ReadFileButton_Click(object sender, EventArgs e)
{
    OpenFileDialog openFileDialog = new OpenFileDialog();
    
    if (openFileDialog.ShowDialog() == DialogResult.OK)
    {
        string filePath = openFileDialog.FileName;
        
        // 使用适当的方式读取文件内容
        // 例如,使用StreamReader来读取文本文件的内容
        using (StreamReader reader = new StreamReader(filePath))
        {
            string fileContent = reader.ReadToEnd();
            
            // 将文件内容显示在文本框中
            fileContentTextBox.Text = fileContent;
        }
    }
}

上記の例では、ユーザーがボタン(ReadFileButton など)をクリックすると、OpenFileDialog ダイアログが表示され、ユーザーが読み込むローカル ファイルを選択できます。ユーザーがファイルを選択して「OK」ボタンをクリックすると、選択したファイルのパス(openFileDialog.FileName)を取得でき、その後、適切なメソッド(StreamReader など)を使用してファイルの内容を読み取ることができます。

bannerAds