Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
590 views
in Technique[技术] by (71.8m points)

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

I've seen many issues like this that have been solved and the problem was mostly due to streams not being disposed of properly.

My issue is slightly different, here follow a code snippet

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

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

Where Images is a custom struct and item.File is the raw data, byte[].

My issue is that at the line where the WriteAllBytes is called, an exception is thrown. The message reads:

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

Again I have no clue how am I going to somehow close the process.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Since File.Create returns the stream i would dispose it properly:

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

or you can use the stream to write to the file directly:

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

or, probably the easiest, use File.WriteAllBytes alone:

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...