C# 异常。文件正被另一个进程使用

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18957309/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 13:41:31  来源:igfitidea点击:

C# exception. File is being used by another process

c#fileprocess

提问by Johan Hjalmarsson

I'm playing around with C# and I encountered a problem. When I try to make a new file, the program breaks and says that the file is being used by another process. It's probably something stupid that I overlooked, but I cant figure it out!

我正在玩 C#,但遇到了一个问题。当我尝试创建一个新文件时,程序中断并说该文件正在被另一个进程使用。这可能是我忽略了一些愚蠢的事情,但我无法弄清楚!

Here is my code:

这是我的代码:

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();
        }
    }
}

Sorry for the long code snippet, but since I'm not sure where the problem originates from I had to include pretty much everything.

抱歉,代码片段很长,但由于我不确定问题出在哪里,因此我不得不包含几乎所有内容。

采纳答案by Arran

Your problem is that File.Createwill open a streamallowing you to do what you like to the file:

你的问题是File.Create会打开一个stream允许你对文件做你喜欢的事情:

http://msdn.microsoft.com/en-us/library/d62kzs03.aspx

http://msdn.microsoft.com/en-us/library/d62kzs03.aspx

A FileStream that provides read/write access to the file specified in path.

提供对路径中指定文件的读/写访问的 FileStream。

Therefore, technically, it is in use already.

因此,从技术上讲,它已经在使用中。

Just remove the File.Createaltogether. The StreamWriterwill handle creating the file if it doesn't exist.

只需将其File.Create完全删除。StreamWriter如果文件不存在,将处理创建文件。

Also, invest in usingconstructs to properly dispose of your file connections too. Will help avoid this in the future.

此外,投资using构建以正确处理您的文件连接。将有助于在未来避免这种情况。

回答by Hamlet Hakobyan

Use

myDropDown_invokedMethod();

instead of

代替

this.BeginInvoke(new MethodInvoker(myDropDown_invokedMethod));

回答by Jeroen van Langen

Thats because the File.Create(NameTb.Text + ".txt");keeps the file open:

那是因为File.Create(NameTb.Text + ".txt"); 保持文件打开:

try use this instead:

尝试改用这个:

    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();
        }
    }

This wil force the File.Createto be Disposed when the method has exits. The dispose will close the filehandle (win32 unmanaged handle). Otherwise the file will be closed by the garbage collector, but you never know when.

这将强制在File.Create方法退出时处理。dispose 将关闭文件句柄(win32 非托管句柄)。否则文件将被垃圾收集器关闭,但你永远不知道什么时候。

回答by Hossain Muctadir

File.Create returns a FileStream object which holds your file. You should use this object for further task.

File.Create 返回一个 FileStream 对象,该对象保存您的文件。您应该将此对象用于进一步的任务。

var fileStream = File.Create(NameTb.Text + ".txt");
//... do all the writing using fileStream
fileStream.Close();

or you could do just

或者你可以做

var fs = File.Create(NameTb.Text + ".txt");
fs.Close();
TextWriter tw = new StreamWriter(NameTb.Text + ".txt"); 
tw.WriteLine("The very first line!");
tw.Close();

回答by NeverHopeless

Your problem seems to be in SaveBtn_Clickevent, you are using your destination file twice for writing:

您的问题似乎SaveBtn_Click发生了,您正在使用目标文件两次进行写入:

File.Create(NameTb.Text + ".txt");
TextWriter tw = new StreamWriter(NameTb.Text + ".txt"); 

Remove this line:

删除这一行:

File.Create(NameTb.Text + ".txt");

回答by kain64b

回答by kain64b

As per MSDN the File.Create Method (String)uses a FileStream which in your case is not being closed. Use something like this:

根据 MSDN File.Create Method (String)使用 FileStream 在您的情况下没有被关闭。使用这样的东西:

FileStream fs = new FileStream(NameTb.Text + ".txt");
File.Create(fs);
fs.Close();

or @Muctadir Dinar

或@Muctadir 第纳尔

var fileStream = File.Create(NameTb.Text + ".txt");
//... do all the writing using fileStream
fileStream.Close();