【发布时间】:2021-07-22 11:50:44
【问题描述】:
这个使用 Windows 窗体的 C# 代码给了我一个错误,说该文件被另一个进程使用,尽管我没有在任何地方打开它。
private void browseBtn2_Click(object sender, EventArgs e)
{
CommonOpenFileDialog dialog = new CommonOpenFileDialog();
dialog.InitialDirectory = "C:\\Users";
dialog.IsFolderPicker = true;
if (dialog.ShowDialog() == CommonFileDialogResult.Ok)
{
MessageBox.Show("You selected: " + dialog.FileName);
this.outputPathText.Text = dialog.FileName;
}
}
private void genBtn_Click(object sender, EventArgs e)
{
string path = outputPathText.Text+@"\test.txt";
TextWriter tw = new StreamWriter(path); //gives me the error here -_-
tw.WriteLine("The very first line!");
tw.Close();
genSuccess.Visible = true;
wait(2000);
genSuccess.Visible = false;
}
【问题讨论】:
-
您在
browseBtn2_Click函数中将文件名设置为this.outputPathText.Text,并在genBtn_Click函数中将其引用为outputPathText.Text。你在genBtn_Click函数中试过this.outputPathText.Text吗? -
在命令提示符下运行:
openfiles /query /fo csv /v > c:\temp\openfiles.txt,然后在openfiles.txt文件中查找test.txt,查看当前锁定了哪个进程。 -
视情况而定,您要么需要弄清楚是哪个进程锁定了文件(参见第一个副本),要么您需要以可以容纳使用同一文件的其他进程的方式访问文件(见其他副本)。请注意,只有后者才是真正的 Stack Overflow 问题。如果您只想知道哪个进程打开了文件,那是一个“通用计算硬件和软件”问题,属于其他地方(例如 superuser.com)。