2

私はメモ帳のクローンに取り組んでいますが、問題が発生しました。テキストボックス内のテキストを作成したファイルに書き込もうとすると、例外が発生します。

別のプロセスで使用されているため、プロセスはファイル 'C:\Users\opeyemi\Documents\b.txt' にアクセスできません。

以下は私が書いたコードです。次に何をすべきかについてアドバイスをいただければ幸いです。

private void Button_Click_1(object sender, RoutedEventArgs e)
{
    SaveFileDialog TextFile = new SaveFileDialog();
    TextFile.ShowDialog();
  // this is the path of the file i wish to save
    string path = System.IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments),TextFile.FileName+".txt");
    if (!System.IO.File.Exists(path))
    {
        System.IO.File.Create(path);
        // i am trying to write the content of my textbox to the file i created
        System.IO.StreamWriter textWriter = new System.IO.StreamWriter(path);
        textWriter.Write(textEditor.Text);
        textWriter.Close();
    }
}
4

1 に答える 1

6

次のように、でのStremWriter使用 (読み取り書き込みの両方 ) を「保護」する必要があります。using

using (System.IO.StreamWriter textWriter = new System.IO.StreamWriter(path))
{
    textWriter.Write(textEditor.Text);
}

必要ありませ.Close()ん。

は必要ありません。はファイルを作成するためです (そして はSystem.IO.File.Create(path);コードで開いたままにしておく を返します)。StreamWriterCreate()FileStream

技術的には、次のことができます。

File.WriteAllText(path, textEditor.Text);

これはオールインワンであり、すべてを実行します (開く、書き込む、閉じる)

または、本当に StreamWriter と File.Create を使用したい場合:

using (System.IO.StreamWriter textWriter = new System.IO.StreamWriter(System.IO.File.Create(path)))
{
    textWriter.Write(textEditor.Text);
}

StreamWriterを受け入れるコンストラクタがありますFileStream

于 2013-08-22T10:48:06.613 に答える