尝试创建或写入文件时发生c#错误

尝试创建或写入文件时发生c#错误,c#,winforms,C#,Winforms,使用Windows窗体的C#中的这段代码给了我一个错误,表示该文件被另一个进程使用,尽管我没有在任何地方打开它 private void browseBtn2_Click(object sender, EventArgs e) { CommonOpenFileDialog dialog = new CommonOpenFileDialog(); dialog.InitialDirectory = "C:\\Users"; dialog.IsFolder

使用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;
}

它可能由程序的旧实例或某个出现故障的进程打开。我建议检查任务管理器并重新启动资源管理器。在MacOS上,我遇到了类似的问题,必须重新启动计算机。

目前不确定这是否是问题的原因,但您的问题可能是因为您没有处理实现IDisposable的对象的习惯

如果一个对象实现了IDisposable,那么该对象的设计者认为它拥有稀缺的资源。应该尽快处理它

我看到的一个问题是,当人们忘记处理对文件的访问时,您不能删除它,因为它仍在使用中

string bitmapFileName = "MyTestFile.bmp";
Bitmap testBitmap = new Bitmap(bitmapFileName);

... // do something with the bitmap. Or not, if you don't want to

// after a while you don't need the bitmap anymore
testBitmap = null;
System.IO.File.Delete(testBitMap);   // Exception! File still in use
尝试将处理实现IDisposable的对象作为一种习惯:

string fileName = outputPathText.Text+@"\test.txt";
using (TextWriter textWriter = File.Create(fileName))
{
    textWriter.WriteLine("The very first line!");
}
就是这样:无需刷新或关闭,对textWriter的处理将为您完成这项工作

同样地:

using (var bmp = new Bitmap(testBitmap))
{
    ... // do something with it, or not if you don't want to
}

// now the bitmap can be deleted
File.Delete(testBitmap);
我不熟悉CommonOpenFileDialog,也不容易找到它的Microsoft说明,但是如果像每个表单一样实现IDisposable,那么也应该处理它:

using (var 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;
    }
}

Dispose将清除CommonOpenFileDialog中的所有内容并释放所有使用的资源。

您在
browseBtn2\u Click
函数中将文件名设置为
this.outputPathText.Text
,并在
genBtn\u Click
函数中将其引用为
outputPathText.Text
。您是否在
genBtn\u Click
函数中尝试了
this.outputPathText.Text
?在命令提示符下运行:
openfiles/query/fo csv/v>c:\temp\openfiles.txt
然后在
openfiles.txt
文件中查找
test.txt
以查看当前锁定了哪个进程。根据情况,您要么需要找出锁定文件的进程(请参见第一个副本),要么需要以能够容纳使用相同文件的其他进程的方式访问文件(请参见其他副本)。请注意,只有后者才是真正的堆栈溢出问题。如果您只想知道哪个进程打开了文件,这是一个“通用计算硬件和软件”问题,属于其他地方(例如superuser.com)。我在任务管理器中没有找到我的程序,但在资源监视器中有带有程序名称的进程。当我试图关闭它时,它会显示“拒绝访问”。我还重新启动了Explorer。您应该尝试重新启动计算机,看看这是否解决了问题。有些进程可能会被窃听,几乎不可能被杀掉,因为它们正在使用一些内核资源。好的,我会试试。谢谢。缺少
Dispose
很容易导致此类问题。