gpt4 book ai didi

c# - "The process cannot access the file because it is being used by another process"图片

转载 作者:太空狗 更新时间:2023-10-29 17:31:39 26 4
gpt4 key购买 nike

我见过很多这样的问题已经解决了,问题主要是由于流没有被正确处理。

我的问题略有不同,这里有一个代码片段

 foreach (Images item in ListOfImages)
{
newPath = Path.Combine(newPath, item.ImageName + item.ImageExtension);
File.Create(newPath);

File.WriteAllBytes(newPath, item.File);
}

其中 Images 是自定义结构,item.File 是原始数据,byte[]。

我的问题是在调用 WriteAllBytes 的那一行抛出了一个异常。消息内容如下:

该进程无法访问该文件,因为它正被另一个进程使用

同样,我不知道如何以某种方式关闭该过程。

最佳答案

由于 File.Create 返回流,我会正确处理它:

using(var stream = File.Create(newPath)){}
File.WriteAllBytes(newPath, item.File);

或者你可以使用流直接写入文件:

using (FileStream fs = File.Create(newPath))
{
fs.Write(item.File, 0, item.File.Length);
}

或者,可能是最简单的,使用 File.WriteAllBytes独自一人:

File.WriteAllBytes(newPath, item.File);

Creates a new file, writes the specified byte array to the file, and then closes the file. If the target file already exists, it is overwritten.

关于c# - "The process cannot access the file because it is being used by another process"图片,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13335349/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com