だから私は学校のプロジェクトのためのWindowsフォームを試してエラーに実行して維持した。なぜStreamReader.Readの周囲でusing(){}を使用すると、後でファイルを削除できますか?
System.IO.IOException('The process cannot access the file 'C:\XXXX\YYYY.txt' because it is being used by another process.'
button_click
イベント経由でファイル(File.Delete(path);
)を削除しようとしたとき。
private void updateTxt(){
String tempStore = "";
iDLbl1.Text = "ID:" + id;//iDLbl1 is ID Label 1
try
{
StreamReader Reader = new StreamReader(path);
while (!Reader.EndOfStream)
{ tempStore += Reader.ReadLine() + "\n"; }
}
catch { noIDLbl.Visible = true; }
rTxtBox.Text = tempStore;//rTxtBox is Rich Text Box
}
private void updateTxt(){
String tempStore = "";
iDLbl1.Text = "ID:" + id;//iDLbl1 is ID Label 1
try
{
using(StreamReader Reader = new StreamReader(path))
{
while (!Reader.EndOfStream)
{ tempStore += Reader.ReadLine() + "\n"; }
}
}
catch { noIDLbl.Visible = true; }
rTxtBox.Text = tempStore;//rTxtBox is Rich Text Box
}
に例外がポップアップ停止:
は私から、次の方法を変更したときに、判明しました。 コードは動作しますが、これはまったく何が原因かわかりません...ロジックは私にとってはクリックしないようですので、誰でもこの問題が発生する理由を知っているか、より論理的な解決方法がありますか?ジャストインケースコンストラクタ:第二のコードで
public FindID(String ID)
{
id = ID;
path = @"C:\XXXX\YYYY\"+ID+".txt";
InitializeComponent();
updateTxt();
}
それは削除することができます前に、はい、ニーズを開いているファイルが再び閉鎖されます。あなたが書いたコードは、File.ReadAllText()の代わりには役に立ちません。 –