C#exception。 文件正由另一个进程使用
我正在玩C#,我遇到了一个问题。 当我尝试创建一个新文件时,程序会断开并说该文件正被另一个进程使用。 这可能是我忽略的愚蠢,但我无法弄明白!
这是我的代码:
using System; using System.IO; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; namespace myNameSpace { public partial class MainWindow : Form { public static string folderPath = @"fullpath"; public MainWindow() { InitializeComponent(); StoredTb.Text = folderPath; String[] files = Directory.GetFiles(folderPath); foreach (string file in files) myDropDown.Items.Add(Path.GetFileNameWithoutExtension(file)); } private void myDropDown_SelectedIndexChanged(object sender, EventArgs e) { this.BeginInvoke(new MethodInvoker(myDropDown_invokedMethod)); } private void myDropDown_invokedMethod() { string fullpath = MainWindow.folderPath + myDropDown.SelectedText + ".txt"; StreamReader sr = new StreamReader(fullpath); NameTb.Text = myDropDown.SelectedText; DescriptionTb.Text = sr.ReadToEnd(); sr.Close(); } private void SaveBtn_Click(object sender, EventArgs e) { File.Create(NameTb.Text + ".txt"); TextWriter tw = new StreamWriter(NameTb.Text + ".txt"); /* this is where the problem occurs */ tw.WriteLine("The very first line!"); tw.Close(); } } }
对于长代码片段感到抱歉,但由于我不确定问题源自何处,因此我必须包含很多内容。
你的问题是File.Create
会打开一个stream
允许你对文件做你喜欢的事情:
http://msdn.microsoft.com/en-us/library/d62kzs03.aspx
FileStream,提供对path中指定的文件的读/写访问权限。
因此,从技术上讲,它已经在使用中。
只需删除File.Create
。 如果文件不存在, StreamWriter
将处理创建文件。
此外,还要投资using
构造来正确处理文件连接。 将来有助于避免这种情况。
使用
myDropDown_invokedMethod();
代替
this.BeginInvoke(new MethodInvoker(myDropDown_invokedMethod));
File.Create返回一个保存文件的FileStream对象。 您应该使用此对象进行进一步的任务。
var fileStream = File.Create(NameTb.Text + ".txt"); //... do all the writing using fileStream fileStream.Close();
或者你可以做到
var fs = File.Create(NameTb.Text + ".txt"); fs.Close(); TextWriter tw = new StreamWriter(NameTb.Text + ".txt"); tw.WriteLine("The very first line!"); tw.Close();
您的问题似乎是在SaveBtn_Click
事件中,您使用目标文件两次写入:
File.Create(NameTb.Text + ".txt"); TextWriter tw = new StreamWriter(NameTb.Text + ".txt");
删除此行:
File.Create(NameTb.Text + ".txt");
根据MSDN, File.Create方法(字符串)使用FileStream,在您的情况下不会被关闭。 使用这样的东西:
FileStream fs = new FileStream(NameTb.Text + ".txt"); File.Create(fs); fs.Close();
或@Muctadir Dinar
var fileStream = File.Create(NameTb.Text + ".txt"); //... do all the writing using fileStream fileStream.Close();
那是因为File.Create(NameTb.Text +“。txt”); 保持文件打开:
尝试使用此代替:
private void SaveBtn_Click(object sender, EventArgs e) { using(Stream stream = File.Create(NameTb.Text + ".txt")) { TextWriter tw = new StreamWriter(stream); /* this is where the problem was */ tw.WriteLine("The very first line!"); tw.Close(); } }
当方法退出时,这将强制File.Create
处理。 dispose将关闭文件句柄(win32非托管句柄)。 否则,垃圾收集器将关闭该文件,但您永远不知道何时。
我看到两种方式:1)使用System.IO.File.WriteAllText http://msdn.microsoft.com/en-us/library/vstudio/8bh11f1k.aspx 2)阅读有关处理http://msdn.microsoft.com /en-us/library/system.idisposable.aspx