Hi friends,
I am creating one small application.
In that I am sending the mail with attachments.
After sending the mail I want to move that attachment files (present on hard drive) to another location in my hard drive.
But whhen I do this, it gives me the exception as shown below,
The process can not access the file because it is being used by another process.
To solve this problem I have written the following code:
string status = Emailer.SendMessageWithAttachment(sendTo, sendFrom, sendSubject, sendMsgBody, sendAttachments); if (status.Equals("101")) { //System.Threading.Thread.Sleep(50000); System.DateTime dt = System.DateTime.Now + new TimeSpan(0, 5, 0); foreach (string strFile in sendAttachments) { try { string strFileName = strFile.Substring(strFile.LastIndexOf('\\')); //while (FileInUse(strFile)) //{ // Thread.Sleep(1000); // if (dt < System.DateTime.Now) // { // MyMessageBox.ShowBox("Original report files not moved to sent items.", "Email Status", MyMessageBox.MyMessageBoxButton.OK, MyMessageBox.MyMessageBoxIcon.Information); // return; // } //} File.Move(strFile, LocalResources.processedInfoDirectory + "Sent Mails" + strFileName); } catch (Exception ex) { MyMessageBox.ShowBox("Error in moving file due to " + ex.Message, "Error", MyMessageBox.MyMessageBoxButton.OK, MyMessageBox.MyMessageBoxIcon.Error); } } status = "Old De-identification status reports successfully sent to " + sendTo + " at " + System.DateTime.Now.ToString() + "."; MyMessageBox.ShowBox(status, "Email Status", MyMessageBox.MyMessageBoxButton.OK, MyMessageBox.MyMessageBoxIcon.Information); } else { MyMessageBox.ShowBox(status, "Email Status", MyMessageBox.MyMessageBoxButton.YesNo, MyMessageBox.MyMessageBoxIcon.Error); } } static bool FileInUse(string path) { try { //Just opening the file as open/create using (FileStream fs = new FileStream(path, FileMode.OpenOrCreate)) { //If required we can check for read/write by using fs.CanRead or fs.CanWrite } return false; } catch (IOException ex) { //check if message is for a File IO if (ex.Message.ToString().Contains("The process cannot access the file")) return true; else throw; } } |
But it is taking lot of time to do the processing (moving).
Please help me to resolve this problem.
Jitendra TiwariPosted Mar 29, 2010, 1:40 PM
this type of exception show when you do not close any open class.
u need to close ur file stream or another
with help of
fs.close()
method to close ur fileStream