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

我已经看到很多这样的问题已经解决了,问题主要是由于流没有被妥善处理。

我的问题略有不同,请按照代码段进行操作

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的行中,抛出exception。 消息如下:

The process cannot access the file because it is being used by another process

我再也不知道如何以某种方式close这个过程。

由于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); 

创建一个新文件,将指定的字节数组写入该文件,然后关闭该文件。 如果目标文件已存在,则会被覆盖。

您声明您的问题与处理流无关,但请查看此MSDN文章:

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

File.Create返回什么? 一个FileStream !!!!

并且,在一天结束时,如果File.WriteAllBytes创建一个文件,如果不存在,为什么File.Create使用File.Create ? ;)

创建一个新文件,将指定的字节数组写入该文件,然后关闭该文件。 如果目标文件已存在,则会被覆盖。

也可以在MSDN上查看它: http : //msdn.microsoft.com/en-us/library/system.io.file.writeallbytes.aspx

 using (FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) 

您的日志可能被写入锁定,因此请尝试使用FileShare.ReadWrite。

create方法打开要写入的文件,并返回一个FileStream对象供您使用。 仅仅因为你没有引用它并不意味着它不需要返回。

 foreach (Images item in ListOfImages) { newPath = Path.Combine(newPath, item.ImageName + item.ImageExtension); FileStream f = File.Create(newPath); f.Write(item.File, 0, item.File.Length); } 

如有必要, File.WriteAllBytes创建该文件。 你可以使用juts:

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

你正确地组合路径吗?

这是完成您要执行的操作的最具体方法:

 foreach (Images item in ListOfImages) { using (System.IO.FileStream output = new System.IO.FileStream(Path.Combine(newPath, item.ImageName + item.ImageExtension), System.IO.FileMode.Create, System.IO.FileAccess.Write)) { output.Write(item.File, 0, item.File.Length); output.Flush(); output.Close(); } } 

您还需要修复用于创建路径的逻辑,这是我在上面的示例中所做的。 你一遍又一遍地连接newPath。

强制垃圾收集器清理。

所以GC.Collect();