1

私は、Visual Studio Ultimate 2012 で Windows フォーム ベースのアプリケーションを作成しています。ファイルを開いて読み取るために、opendialog を配置しました。コードは次のとおりです。

private void button1_Click(object sender, System.EventArgs e)
{
Stream myStream = null;
OpenFileDialog openFileDialog1 = new OpenFileDialog();

openFileDialog1.InitialDirectory = "c:\\" ;
openFileDialog1.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*" ;
openFileDialog1.FilterIndex = 2 ;
openFileDialog1.RestoreDirectory = true ;

if(openFileDialog1.ShowDialog() == DialogResult.OK)
{
    try
    {
        if ((myStream = openFileDialog1.OpenFile()) != null)
        {
            using (myStream)
            {
                // Insert code to read the stream here.
            }
        }
    }
    catch (Exception ex)
    {
        MessageBox.Show("Error: Could not read file from disk. Original error: " + ex.Message);
    }
}

}

しかし、これを実行しようとするたびに、ブラウザー ウィンドウからファイルを選択すると、既定のディレクトリ (Documents/VisualStudio/Projects/WindowsFormApplication/bin/debug/ にあります) でファイルを検索するため、filenotfound 例外が表示されます。 openFileDialog1) であり、指定したディレクトリにはありません。助けてください!!

4

1 に答える 1

1

問題は次の行です

openFileDialog1.RestoreDirectory = true;

これにより、ダイアログが閉じられると、現在のディレクトリが元のディレクトリにリセットされます。メソッドはOpenFile相対パスを使用しているため、ダイアログが終了した場所ではなく、ダイアログが開始したファイルを開こうとしているようです。

RestoreDirectoryファイルの使用が終わったら、設定を削除して手動でパスをリセットしてみてください

于 2013-03-26T15:18:39.017 に答える