How to avoid exception "File used by another process"? [duplicate] - c#

I'm trying to programmically delete a file, but the file is apparently being used by another process (which happens to be my program). Basically, the program loads images from a folder by using FromUri to create a Bitmap, which is then loaded into an Image array, which in turn becomes the child of a stackpanel. Not very efficient, but it works.
I've tried clearing the stackpanel's children, and making the images in the array null, but I'm still getting the IOException telling me that the file is being used by another process.
Is there some other way to remove the file from my application's processes?

it may be Garbage Collection issue.
System.GC.Collect();
System.GC.WaitForPendingFinalizers();
File.Delete(picturePath);

In order to release an image file after loading, you have to create your images by setting the BitmapCacheOption.OnLoad flag. One way to do this would be this:
string filename = ...
BitmapImage image = new BitmapImage();
image.BeginInit();
image.CacheOption = BitmapCacheOption.OnLoad;
image.UriSource = new Uri(filename);
image.EndInit();
Although setting BitmapCacheOption.OnLoad works on a BitmapImage that is loaded from a local file Uri, this is afaik nowhere documented. Therefore a probably better or safer way is to load the image from a FileStream, by setting the StreamSource property instead of UriSource:
string filename = ...
BitmapImage image = new BitmapImage();
using (var stream = File.OpenRead(filename))
{
image.BeginInit();
image.CacheOption = BitmapCacheOption.OnLoad;
image.StreamSource = stream;
image.EndInit();
}

Another way is to delete file. Load your file using FileStream class and release an file
through stream.Dispose();
it will never give you the Exception "The process cannot access the file '' because it is being used by another process."
using (FileStream stream = new FileStream("test.jpg", FileMode.Open, FileAccess.Read))
{
pictureBox1.Image = Image.FromStream(stream);
stream.Dispose();
}
// delete your file.
File.Delete(delpath);

var uploadedFile = Request.Files[0]; //Get file
var fileName = Path.GetFileName(uploadedFile.FileName); //get file name
string fileSavePath = Server.MapPath(fileName); //get path
uploadedFile.SaveAs(fileSavePath); //saving file
FileInfo info = new FileInfo(fileSavePath);//get info file
//the problem ocurred because this,
FileStream s = new FileStream(fileSavePath, FileMode.Open); //openning stream, them file in use by a process
System.IO.File.Delete(fileSavePath); //Generete a error
//problem solved here...
s.Close();
s.Dispose();
System.IO.File.Delete(fileSavePath); //File deletad sucessfully!

I had the similar issue. The only difference was that I was using Binding(MVVM Pattern). Nothing much worked then I removed everything and tried with Binding Mode=OneWay along with GC.Collect() before calling File.Delete(path) and it worked finally.

I had the same issue. The problem I had was with the openFileDialog and saveFileDialog having the following set:
MyDialog.AutoUpgradeEnabled = false;
I commented out that line and it was resolved.

In my case, I started a new process of devenv.exe opening a temporary solution file. After the process was ended, I found I could not delete the directory for few minutes. Checking with "resmon", resource monitor, I found it was a executable called PerfWatson2.exe that was using the temp file. Looking at the site, PerfWatson is actually a Visual Studio Customer Experience Improvement Program from MicroSoft. It will lock the file or directory you temporarily used even after you have ended the VS IDE.
The solution is to disable the Visual Studio Customer Experience Improvement Program, see this. This shoudln't be an issue after your app is publihsed. But it is quite annoying during debuging.

Related

Saving a bitmap which is being used C# [duplicate]

I'm trying to programmically delete a file, but the file is apparently being used by another process (which happens to be my program). Basically, the program loads images from a folder by using FromUri to create a Bitmap, which is then loaded into an Image array, which in turn becomes the child of a stackpanel. Not very efficient, but it works.
I've tried clearing the stackpanel's children, and making the images in the array null, but I'm still getting the IOException telling me that the file is being used by another process.
Is there some other way to remove the file from my application's processes?
it may be Garbage Collection issue.
System.GC.Collect();
System.GC.WaitForPendingFinalizers();
File.Delete(picturePath);
In order to release an image file after loading, you have to create your images by setting the BitmapCacheOption.OnLoad flag. One way to do this would be this:
string filename = ...
BitmapImage image = new BitmapImage();
image.BeginInit();
image.CacheOption = BitmapCacheOption.OnLoad;
image.UriSource = new Uri(filename);
image.EndInit();
Although setting BitmapCacheOption.OnLoad works on a BitmapImage that is loaded from a local file Uri, this is afaik nowhere documented. Therefore a probably better or safer way is to load the image from a FileStream, by setting the StreamSource property instead of UriSource:
string filename = ...
BitmapImage image = new BitmapImage();
using (var stream = File.OpenRead(filename))
{
image.BeginInit();
image.CacheOption = BitmapCacheOption.OnLoad;
image.StreamSource = stream;
image.EndInit();
}
Another way is to delete file. Load your file using FileStream class and release an file
through stream.Dispose();
it will never give you the Exception "The process cannot access the file '' because it is being used by another process."
using (FileStream stream = new FileStream("test.jpg", FileMode.Open, FileAccess.Read))
{
pictureBox1.Image = Image.FromStream(stream);
stream.Dispose();
}
// delete your file.
File.Delete(delpath);
var uploadedFile = Request.Files[0]; //Get file
var fileName = Path.GetFileName(uploadedFile.FileName); //get file name
string fileSavePath = Server.MapPath(fileName); //get path
uploadedFile.SaveAs(fileSavePath); //saving file
FileInfo info = new FileInfo(fileSavePath);//get info file
//the problem ocurred because this,
FileStream s = new FileStream(fileSavePath, FileMode.Open); //openning stream, them file in use by a process
System.IO.File.Delete(fileSavePath); //Generete a error
//problem solved here...
s.Close();
s.Dispose();
System.IO.File.Delete(fileSavePath); //File deletad sucessfully!
I had the similar issue. The only difference was that I was using Binding(MVVM Pattern). Nothing much worked then I removed everything and tried with Binding Mode=OneWay along with GC.Collect() before calling File.Delete(path) and it worked finally.
I had the same issue. The problem I had was with the openFileDialog and saveFileDialog having the following set:
MyDialog.AutoUpgradeEnabled = false;
I commented out that line and it was resolved.
In my case, I started a new process of devenv.exe opening a temporary solution file. After the process was ended, I found I could not delete the directory for few minutes. Checking with "resmon", resource monitor, I found it was a executable called PerfWatson2.exe that was using the temp file. Looking at the site, PerfWatson is actually a Visual Studio Customer Experience Improvement Program from MicroSoft. It will lock the file or directory you temporarily used even after you have ended the VS IDE.
The solution is to disable the Visual Studio Customer Experience Improvement Program, see this. This shoudln't be an issue after your app is publihsed. But it is quite annoying during debuging.

C# Application, unable to delete image because the system has it locked [duplicate]

I'm trying to programmically delete a file, but the file is apparently being used by another process (which happens to be my program). Basically, the program loads images from a folder by using FromUri to create a Bitmap, which is then loaded into an Image array, which in turn becomes the child of a stackpanel. Not very efficient, but it works.
I've tried clearing the stackpanel's children, and making the images in the array null, but I'm still getting the IOException telling me that the file is being used by another process.
Is there some other way to remove the file from my application's processes?
it may be Garbage Collection issue.
System.GC.Collect();
System.GC.WaitForPendingFinalizers();
File.Delete(picturePath);
In order to release an image file after loading, you have to create your images by setting the BitmapCacheOption.OnLoad flag. One way to do this would be this:
string filename = ...
BitmapImage image = new BitmapImage();
image.BeginInit();
image.CacheOption = BitmapCacheOption.OnLoad;
image.UriSource = new Uri(filename);
image.EndInit();
Although setting BitmapCacheOption.OnLoad works on a BitmapImage that is loaded from a local file Uri, this is afaik nowhere documented. Therefore a probably better or safer way is to load the image from a FileStream, by setting the StreamSource property instead of UriSource:
string filename = ...
BitmapImage image = new BitmapImage();
using (var stream = File.OpenRead(filename))
{
image.BeginInit();
image.CacheOption = BitmapCacheOption.OnLoad;
image.StreamSource = stream;
image.EndInit();
}
Another way is to delete file. Load your file using FileStream class and release an file
through stream.Dispose();
it will never give you the Exception "The process cannot access the file '' because it is being used by another process."
using (FileStream stream = new FileStream("test.jpg", FileMode.Open, FileAccess.Read))
{
pictureBox1.Image = Image.FromStream(stream);
stream.Dispose();
}
// delete your file.
File.Delete(delpath);
var uploadedFile = Request.Files[0]; //Get file
var fileName = Path.GetFileName(uploadedFile.FileName); //get file name
string fileSavePath = Server.MapPath(fileName); //get path
uploadedFile.SaveAs(fileSavePath); //saving file
FileInfo info = new FileInfo(fileSavePath);//get info file
//the problem ocurred because this,
FileStream s = new FileStream(fileSavePath, FileMode.Open); //openning stream, them file in use by a process
System.IO.File.Delete(fileSavePath); //Generete a error
//problem solved here...
s.Close();
s.Dispose();
System.IO.File.Delete(fileSavePath); //File deletad sucessfully!
I had the similar issue. The only difference was that I was using Binding(MVVM Pattern). Nothing much worked then I removed everything and tried with Binding Mode=OneWay along with GC.Collect() before calling File.Delete(path) and it worked finally.
I had the same issue. The problem I had was with the openFileDialog and saveFileDialog having the following set:
MyDialog.AutoUpgradeEnabled = false;
I commented out that line and it was resolved.
In my case, I started a new process of devenv.exe opening a temporary solution file. After the process was ended, I found I could not delete the directory for few minutes. Checking with "resmon", resource monitor, I found it was a executable called PerfWatson2.exe that was using the temp file. Looking at the site, PerfWatson is actually a Visual Studio Customer Experience Improvement Program from MicroSoft. It will lock the file or directory you temporarily used even after you have ended the VS IDE.
The solution is to disable the Visual Studio Customer Experience Improvement Program, see this. This shoudln't be an issue after your app is publihsed. But it is quite annoying during debuging.

WPF load image from folder

I have images that is not located in resources but on the disk. The folder is relative to application. I used:
Overview_Picture.Source = new BitmapImage(new Uri(String.Format("file:///{0}/../MyImages /myim.jpg", Directory.GetCurrentDirectory())));
Overview_Picture.Source = new BitmapImage(uriSource);
But those type of code created many problems and messed up GetCurrentDirectory returns that sometime ok and some times not.
So, MyImages folder is located next to Debug folder, how can I use them images there and not as I done, In some other more right way?
As mentioned oftentimes here on SO, the GetCurrentDirectory method does by definition not always return the directory your assembly resides in, but the current working directory. There is a big difference between the two.
What you need is the current assembly folder (and the parent of that). Also, I'm not sure whether it is wanted that the pictures are one folder above the installation folder (which is basically what you're saying when you say they are one level above the Debug folder - in real life that would be one folder above the folder the application is installed to).
Use the following:
string currentAssemblyPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
string currentAssemblyParentPath = Path.GetDirectoryName(currentAssemblyPath);
Overview_Picture.Source = new BitmapImage(new Uri(String.Format("file:///{0}/MyImages/myim.jpg", currentAssemblyParentPath)));
Also, there's a stray space after MyImages, which I removed.
An alternative to constructing an absolute Uri from a relative file path would be to just open a FileStream from the relative path, and assign that to the BitmapImage's StreamSource property. Note however that you also have to set BitmapCacheOption.OnLoad when you want to close the stream right after initializing the BitmapImage.
var bitmap = new BitmapImage();
using (var stream = new FileStream("../MyImages/myim.jpg", FileMode.Open))
{
bitmap.BeginInit();
bitmap.CacheOption = BitmapCacheOption.OnLoad;
bitmap.StreamSource = stream;
bitmap.EndInit();
bitmap.Freeze(); // optional
}
Overview_Picture.Source = bitmap;

How to avoid from The process cannot access the file XXX.XXX because it is being used by another process

I transfer file from computer to computer Through a WebService.
After the file was transfer I need to read its size.
When I try to read the file size I get:
The process cannot access the file XXX.XXX because it is being used by another process
What can I do to avoid this error?
i read the file like this:
LocalFileSize = File.Open(TermSendName, FileMode.Open, FileAccess.Read).Length.ToString();
how to close this ?
I guess that you are using a FileStream to read the file.
Close the stream when the transfer has completed.
Try this
FileStream stream = File.Open(TermSendName, FileMode.Open, FileAccess.Read);
LocalFileSize = stream.Length.ToString();
stream.Close();
If you only want to get length of file you can also do something like
FileInfo fileInfo = new FileInfo(fileName);
string size = fileInfo.Length.ToString();
Please check the following Stack Overflow link, I faced the same issue and got fixed here:
The process cannot access the file because it is being used by another process.c#

Set permissions on folder used by winform application

My winform application periodically pulls a flash file from an SQL database, writes it to a temporary folder, displays it in a webbroswer control, and then deletes it from the temporary folder. My application creates the temporary folder if it does not exist. The temporary folder is located in 'System.Environment.CurrentDirectory'.
My problem is the permissions of the temporary folder frequently become read only and then my application cannot delete the file. Sometimes the problem occurs immediately, and sometimes I can run the application several times before it occurs.
How do I insure that the file is deleted?
I added code to delete the temporary folder and then re-create it each time it writes to it, but this did not resolve my problem.
Only my application needs to access this folder, and the folder only holds these flash images.
I thought about using the generic 'temp' folder, but read somewhere that that could lead to problems.
Also, I got the same problem when I located the temporary folder at 'D:\'.
I'm using VS2008 on Windows XP. The application is to run on XP, Vista and 7.
Here is code.
DataSet dsFlashQuizRandom = new DataSet();
dsFlashQuizRandom = objUserDAO.GetFlashQuizRandom(intAge);
if (dsFlashQuizRandom.Tables[0].Rows[0]["large_image_blob"] != null && dsFlashQuizRandom.Tables[0].Rows[0]["file_name"].ToString().Trim() != string.Empty)
{
byte[] b = (byte[])dsFlashQuizRandom.Tables[0].Rows[0]["large_image_blob"];
if (b != null)
{
string flashFileName = dsFlashQuizRandom.Tables[0].Rows[0]["file_name"].ToString().Trim();
string targetPath = System.Environment.CurrentDirectory.ToString() + #"\images\";
string strFileName = targetPath + flashFileName;
//Delete the current version of the folder (if it exists); then create a new version of it.
if (System.IO.Directory.Exists(targetPath))
System.IO.Directory.Delete(targetPath, true);
if (!System.IO.Directory.Exists(targetPath))
System.IO.Directory.CreateDirectory(targetPath);
//Write the file to a FileStream, assign that stream to the webbrowser control.
FileStream fs = new FileStream(strFileName, FileMode.CreateNew, FileAccess.Write);
fs.Write(b, 0, b.Length);
fs.Close();
webBrowserQuizFlash.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(webBrowserQuizFlash_DocumentCompleted);
webBrowserQuizFlash.Url = new System.Uri(strFileName, System.UriKind.Absolute);
}
}
//Delete the Flash Webbrowser file once it has completed loading.
private void webBrowserQuizFlash_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
FileInfo fi = new FileInfo(strFileName);
try
{
fi.Delete();
}
catch (IOException ex)
{
MessageBox.Show("IOException = " + ex); //test code
}
}
Any suggestions or a point in the right direction would be appreciated.
Cheers,
Frederick
PS--When copying my code to this post I see the color of the text is all red after the #"\images\"; Is there a problem with this part of my code, or is this a display artifact? Should I use this instead: #"\images\\";
You could use System.IO.Path.GetTempPath() to get a temp folder to use.
I assume that you're having problems with the delete due to the file being locked by some process. You might be able to get around that by using the MoveFileEx function to delete it at next reboot.
I think the accessing problem comes from another application that locks the file. One common application group that does such things would be the on access scanner from your anti-virus program.
To get a deeper look into, who accesses your file you should take a deeper look with Process Monitor to find out who will block your file.
Also you can maybe make a little change to your code:
//Write the file to a FileStream, assign that stream to the webbrowser control.
using(FileStream fs = new FileStream(strFileName, FileMode.CreateNew, FileAccess.Write))
{
fs.Write(b, 0, b.Length);
}

Categories

Resources