Solved

Cannot access

Posted on 2006-07-22
51
323 Views
Last Modified: 2012-08-13
Why does I get this error?
objFileStream = new FileStream(Server.MapPath(fName), FileMode.Create, FileAccess.ReadWrite);
//The process cannot access the file 'C:\Documents and Settings\All Users\Dokumenter\www\myFile.csv' because it is being used by another process.
I don't use it another place I think.....
0
Comment
Question by:m-jansen
  • 38
  • 7
  • 5
  • +1
51 Comments
 

Author Comment

by:m-jansen
Comment Utility
System.IO.IOException: The process cannot access the file 'C:\Documents and Settings\All Users\Dokumenter\dhh\www\myFile.csv' because it is being used by another process. at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath) at System.IO.FileStream.Init(String path, FileMode mode, FileAccess access, Int32 rights, Boolean useRights, FileShare share, Int32 bufferSize, FileOptions options, SECURITY_ATTRIBUTES secAttrs, String msgPath, Boolean bFromProxy) at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access) at util.Email.GetTableData(DataTable dt) in c:\Documents and Settings\All Users\Dokumenter\dhh\www\App_Code\Email.cs:line 53
0
 
LVL 96

Expert Comment

by:Bob Learned
Comment Utility
Are you closing the FileStream after you use it?  What is the timing of things?

Bob
0
 
LVL 8

Expert Comment

by:Maher-Jendasi
Comment Utility
Please use RegMon from Sysinternals.com to see why the file is locked (being used by another process) at the time you try to execute that line of code
0
 

Author Comment

by:m-jansen
Comment Utility
Yes. I close it this error does occur before I close it. I'm running it in the constructor... maybe that's the problem.
0
 

Author Comment

by:m-jansen
Comment Utility
Maher-Jendasi: What should I filer out to see what I need to see with RegMon?
0
 

Author Comment

by:m-jansen
Comment Utility
TheLearnedOne: What about the timing? How to debug this?
0
 
LVL 96

Assisted Solution

by:Bob Learned
Bob Learned earned 100 total points
Comment Utility
Ok, this is what I was thinking, but you need to explain something.  You open the FileStream, and then close it, and then within a very short period of time, you try to access it again--bam!!  I just need to have a bigger picture of what is going on to be able to tell.

So, what are you doing here?

Bob
0
 

Author Comment

by:m-jansen
Comment Utility
Well, I am doing a lot of things actually. But there is no open method right? Only close method?

Is it possible to make a mechanism that wait's until the process is free?
0
 
LVL 96

Expert Comment

by:Bob Learned
Comment Utility
The constructor parameters in the new is the "open" method, and then the Close/Dispose method.

Is this a problem with the file actually being in use by another process, and not your application?

Bob
0
 

Author Comment

by:m-jansen
Comment Utility
well, the file I try to overwrite to is beeing showed in the solution explorer..... that's the only place I can think of
0
 
LVL 96

Expert Comment

by:Bob Learned
Comment Utility
Is it included as part of the solution?  Or is it just shown when you have "Show All Files"?

Bob
0
 

Author Comment

by:m-jansen
Comment Utility
It is showed in "Nest related files"
0
 

Author Comment

by:m-jansen
Comment Utility
I tried to delete it from the solution and then my script would run. It created a new file. But when trying to run the script one more time it didn't work. I then tried to refresh my solution to se the new created file then delete the file again, but now I can't delete. I get this error message from Visual Studio 2005:

Error deleting myFile.csv. Unable to delete myFile.csv. The process cannot get access to the file because it is used by another process.

What process? I'm not running the webpage in the background.
0
 

Author Comment

by:m-jansen
Comment Utility
here is the method I use...


using System.Net;
using System.Net.Mail;
using System.IO;
using System.Net.Mime;
using System.Data.OleDb;


        protected string error;

        OleDbConnection Conn;
        OleDbDataAdapter Da;
        DataSet Ds = new DataSet();
        DataTable Dt;
        DataTable DtSammendrag = new DataTable();

        private void GetTableData(DataTable dt)
        {

Conn = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + Server.MapPath("../../App_Data/db.mdb") + "");            
            try
            {
                string strLine = "";
                string fName;
                FileStream objFileStream;
                StreamWriter objStreamWriter;

                fName = "myFile.csv";                

                objFileStream = new FileStream(Server.MapPath(fName), FileMode.Create, FileAccess.ReadWrite);
                objStreamWriter = new StreamWriter(objFileStream);

                StringBuilder TableData = new StringBuilder();
                // retrieve header row column labels
                foreach (DataColumn dc in dt.Columns)
                {
                    strLine += dc.ColumnName + ";";
                }
                objStreamWriter.WriteLine(strLine);
                // retrieve rows
                strLine = "";
                foreach (DataRow dr in dt.Rows)
                {
                    strLine = "";
                    foreach (DataColumn dc in dt.Columns)
                    {
                        strLine += dr[dc] + ";";
                    }
                    objStreamWriter.WriteLine(strLine);
                    objStreamWriter.WriteLine("\n");

                }

                objStreamWriter.Close();
                objFileStream.Close();
            }
            catch (Exception ex)
            {
                error += ex.ToString();
            }
        }
0
 

Author Comment

by:m-jansen
Comment Utility
and

        public void LoadRequests()
        {
            string StrSel = "SELECT * FROM [Bestillinger_Ikke_Sendt]";
            Da = new OleDbDataAdapter(StrSel, Conn);
            Ds.Tables.Add("Ikke sendt");
            Da.Fill(Ds, "Ikke sendt");
            Dt = Ds.Tables["Ikke sendt"];
            GetTableData(Dt);
        }
0
 

Author Comment

by:m-jansen
Comment Utility
I get the error on this line

objFileStream = new FileStream(Server.MapPath(fName), FileMode.Create, FileAccess.ReadWrite);
0
 

Author Comment

by:m-jansen
Comment Utility
After choosing Build -> Rebuild Solution it was possible to delete the file again..... strange things.
0
 

Author Comment

by:m-jansen
Comment Utility
I have tried to run the page in IIS but then I get some more strange problems.... I have posted about it here:
http://www.experts-exchange.com/Programming/Programming_Languages/Dot_Net/ASP_DOT_NET/Q_21928801.html
0
 

Author Comment

by:m-jansen
Comment Utility
I also run this in a Global.asax.

<%@ Import Namespace="util" %>

<script runat="server">

    protected void Application_BeginRequest(object sender, EventArgs e)
    {
        // Code that runs when a new session is started
        if (Application["LastScheduledRun"] == null)
        {
            Application["LastScheduledRun"] = DateTime.Now;
            //Label1.Text = "No send. First time." + Application["LastScheduledRun"];
            Email mail = new Email();
            mail.SendMail();
        }
        else
        {
            //Label1.Text += "Will run at first hit after 00:00 O'clock." + (((TimeSpan)(DateTime.Now - Convert.ToDateTime(Application["LastScheduledRun"]))).Minutes);
        }

        if ((((TimeSpan)(DateTime.Now - Convert.ToDateTime(Application["LastScheduledRun"]))).Minutes) > 0)
        {
            Email mail = new Email();
            mail.SendMail();

            Application.Lock();
            Application["LastScheduledRun"] = DateTime.Now;
            Application.UnLock();
            //Label1.Text = "Mail is sent at:" + Application["LastScheduledRun"];
        }
0
 

Author Comment

by:m-jansen
Comment Utility
It did not make any difference to remove the Global.asax
0
 

Author Comment

by:m-jansen
Comment Utility
Actually it always works one time after rebuilding the solution.... so it looks like there is something that not stops to run. But I don't know what.
0
 

Author Comment

by:m-jansen
Comment Utility
Does anyone follow me? Or should I make a new and better question?
0
 
LVL 96

Expert Comment

by:Bob Learned
Comment Utility
No, please don't start another question, we can get this.  I still don't understand what the .csv file is, and why it would be listed as part of the solution, unless it is just being displayed because it is in the same folder as the solution.  Are you reading from an Access database and writing values into a .csv file, or the other way around?

Bob
0
 

Author Comment

by:m-jansen
Comment Utility
>Are you reading from an Access database and writing values into a .csv file, or the other way around?
yes
>unless it is just being displayed because it is in the same folder as the solution
I think that's the only thing it does..... Else it would be a bug in the Visual Studio I guess.
0
 

Author Comment

by:m-jansen
Comment Utility
writing values into a .csv file is what I do
0
Threat Intelligence Starter Resources

Integrating threat intelligence can be challenging, and not all companies are ready. These resources can help you build awareness and prepare for defense.

 
LVL 12

Expert Comment

by:TheMegaLoser
Comment Utility
Are you creating multiple instances of the object?
0
 

Author Comment

by:m-jansen
Comment Utility
No. This is how I create it.

    protected void Button1_Click(object sender, EventArgs e)
    {
        Email mail = new Email();
        mail.LoadRequests();
        mail.SendMail();
        Label2.Text = mail.GetErrors();
    }
0
 

Author Comment

by:m-jansen
Comment Utility
Why can't I delete the file that the script create manualy?

I tried to delete it from the solution and then my script would run. It created a new file. But when trying to run the script one more time it didn't work. I then tried to refresh my solution to se the new created file then delete the file again, but now I can't delete. I get this error message from Visual Studio 2005:

Error deleting myFile.csv. Unable to delete myFile.csv. The process cannot get access to the file because it is used by another process.

What process? I'm not running the webpage in the background.
0
 
LVL 12

Expert Comment

by:TheMegaLoser
Comment Utility
If you're not running VS 2005 (make sure the process is not running using the Task Manager) but accessing the page, does it work then?
0
 

Author Comment

by:m-jansen
Comment Utility
I've tested this with IIS now and get the same problem there, but now I have to restart the machine or rebuild the solution in order to shut down the process that I don't know what is. I tried to look in the taskmanager at the same time as I loaded the web page.

aspnet_wp.exe (user: ASPNET)starts to use arround 30mb at the same time as I load the page. What process shall I look for?
0
 
LVL 12

Expert Comment

by:TheMegaLoser
Comment Utility
Probably. It depends on which version of IIS you're using.

IIS5 = aspnet_wp
IIS6 = w3wp

One thing that catches my eye in your code, if you get an error you don't close the filestreams:

....
                objStreamWriter.Close();
                objFileStream.Close();
            }
            catch (Exception ex)
            {
                error += ex.ToString();
            }

A good practice would be to always close them. Have you tried placing a breakpoint at the close statements to see that they're really executed? Are there any exceptions thrown?
0
 

Author Comment

by:m-jansen
Comment Utility
After doing like you said to place a breakpoint at the close statements I can see that the close statements are runned every time.... but now it also works to run the script several times after each other with no errors! Strange. I didn't do anything else than to add breakpoints. It works when I remove the breakpoints too. very strange.
0
 

Author Comment

by:m-jansen
Comment Utility
sorry... I did do something. I removed mail.SendMail(); in this code.... But then the error was gone.

    protected void Button1_Click(object sender, EventArgs e)
    {
        Email mail = new Email();
        mail.LoadRequests();
        ///mail.SendMail();
        Label2.Text = mail.GetErrors();
    }
0
 

Author Comment

by:m-jansen
Comment Utility
The code stops here in my SendMail() on the second run.

Attachment data = new Attachment(Server.MapPath(file), MediaTypeNames.Application.Octet);
0
 
LVL 12

Accepted Solution

by:
TheMegaLoser earned 150 total points
Comment Utility
If your data has changed it can explain this. Other data may produce an error and thus leading to the streams not being closed.

Move the Close statements to a finally clause to be on the safe side.
0
 

Author Comment

by:m-jansen
Comment Utility
On the second run the close statements are not ran. Only the first time. Why?

This is the exception I get.

System.IO.IOException: The process cannot access the file 'C:\Documents and Settings\All Users\Dokumenter\dhh\www\01_hovedsider\02_produkter\myFile.csv' because it is being used by another process. at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath) at System.IO.FileStream.Init(String path, FileMode mode, FileAccess access, Int32 rights, Boolean useRights, FileShare share, Int32 bufferSize, FileOptions options, SECURITY_ATTRIBUTES secAttrs, String msgPath, Boolean bFromProxy) at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access) at _01_hovedsider_02_produkter_TestLastScheduledRun.GetTableData(DataTable dt) in c:\Documents and Settings\All Users\Dokumenter\dhh\www\01_hovedsider\02_produkter\TestLastScheduledRun.aspx.cs:line 49
0
 

Author Comment

by:m-jansen
Comment Utility
I have not moved the colse statements yet...
0
 

Author Comment

by:m-jansen
Comment Utility
what does finally clause means?
0
 

Author Comment

by:m-jansen
Comment Utility
and where to place it
0
 

Author Comment

by:m-jansen
Comment Utility
this is the line where the exeption occur....
objFileStream = new FileStream(Server.MapPath(fName), FileMode.Create, FileAccess.ReadWrite);

and this is where it stops when using breakpoints
Attachment data = new Attachment(Server.MapPath(file), MediaTypeNames.Application.Octet);
0
 
LVL 12

Assisted Solution

by:TheMegaLoser
TheMegaLoser earned 150 total points
Comment Utility
0
 

Author Comment

by:m-jansen
Comment Utility
ok. I understand how to use finally now, but it didn't help...

This is how it looks like now

    private void GetTableData(DataTable dt)
    {

        string strLine = "";
        string fName;
        FileStream objFileStream;
        StreamWriter objStreamWriter;

        fName = "myFile.csv";

        objFileStream = new FileStream(Server.MapPath(fName), FileMode.Create, FileAccess.ReadWrite);
        objStreamWriter = new StreamWriter(objFileStream);

        StringBuilder TableData = new StringBuilder();

        try
        {
            // retrieve header row column labels
            foreach (DataColumn dc in dt.Columns)
            {
                strLine += dc.ColumnName + ";";
            }
            objStreamWriter.WriteLine(strLine);
            // retrieve rows
            strLine = "";
            foreach (DataRow dr in dt.Rows)
            {
                strLine = "";
                foreach (DataColumn dc in dt.Columns)
                {
                    strLine += dr[dc] + ";";
                }
                objStreamWriter.WriteLine(strLine);
            }
        }


        catch (Exception ex)
        {
            error += ex.ToString();
        }
        finally
        {
            objStreamWriter.Close();
            objFileStream.Close();
        }
    }


but it still stops at         objFileStream = new FileStream(Server.MapPath(fName), FileMode.Create, FileAccess.ReadWrite); on the second run.


Stack Trace:


[IOException: The process cannot access the file 'C:\Documents and Settings\All Users\Dokumenter\dhh\www\01_hovedsider\02_produkter\myFile.csv' because it is being used by another process.]
   System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath) +2015117
   System.IO.FileStream.Init(String path, FileMode mode, FileAccess access, Int32 rights, Boolean useRights, FileShare share, Int32 bufferSize, FileOptions options, SECURITY_ATTRIBUTES secAttrs, String msgPath, Boolean bFromProxy) +998
   System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access) +57
   _01_hovedsider_02_produkter_TestLastScheduledRun.GetTableData(DataTable dt) in c:\Documents and Settings\All Users\Dokumenter\dhh\www\01_hovedsider\02_produkter\TestLastScheduledRun.aspx.cs:47
   _01_hovedsider_02_produkter_TestLastScheduledRun.LoadRequests() in c:\Documents and Settings\All Users\Dokumenter\dhh\www\01_hovedsider\02_produkter\TestLastScheduledRun.aspx.cs:92
   _01_hovedsider_02_produkter_TestLastScheduledRun.Button1_Click(Object sender, EventArgs e) in c:\Documents and Settings\All Users\Dokumenter\dhh\www\01_hovedsider\02_produkter\TestLastScheduledRun.aspx.cs:166
   System.Web.UI.WebControls.Button.OnClick(EventArgs e) +96
   System.Web.UI.WebControls.Button.RaisePostBackEvent(String eventArgument) +117
   System.Web.UI.WebControls.Button.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(String eventArgument) +31
   System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl, String eventArgument) +32
   System.Web.UI.Page.RaisePostBackEvent(NameValueCollection postData) +72
   System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +3837

 
0
 

Author Comment

by:m-jansen
Comment Utility
I think the problem occur when I try to send the mail. It looks like somehting won't shut down after I send the mail. Here is the code I use to send mail.

    public void SendMail()
    {
        if (DoesAnyNeedToBeSent() == true)
        {
            try
            {
                MailMessage mail = new MailMessage();
                //mail.To.Add(TxtEpost.Text);
                mail.To.Add("tesdfsdf@yahoo.com");
                mail.From = new MailAddress("mr_tesdfsdf@yahoo.com", "DHH", System.Text.Encoding.UTF8);

                mail.Subject = "Bestille katalog (autoresponse)";
                mail.SubjectEncoding = System.Text.Encoding.UTF8;

                string body = "";
                //body += "Hei " + TxtEtternavnForrnavn.Text + "\n\n"

                mail.Body = body;

                // Create  the file attachment for this e-mail message.
                string file = "myFile.csv";
                Attachment data = new Attachment(Server.MapPath(file), MediaTypeNames.Application.Octet);
                // Add time stamp information for the file.
                ContentDisposition disposition = data.ContentDisposition;
                disposition.CreationDate = System.IO.File.GetCreationTime(Server.MapPath(file));
                disposition.ModificationDate = System.IO.File.GetLastWriteTime(Server.MapPath(file));
                disposition.ReadDate = System.IO.File.GetLastAccessTime(Server.MapPath(file));
                // Add the file attachment to this e-mail message.
                mail.Attachments.Add(data);

                mail.BodyEncoding = System.Text.Encoding.UTF8;
                mail.IsBodyHtml = false;
                mail.Priority = MailPriority.High;
                //Add the Creddentials
                SmtpClient client = new SmtpClient();
                client.Credentials = new System.Net.NetworkCredential("myname@gmail.com", "aasds");
                client.Port = 587;//or use 587, 465 or 587
                client.Host = "smtp.gmail.com";
                client.EnableSsl = true;                
                client.Send(mail);
                //client.SendCompleted += new SendCompletedEventHandler(client_SendCompleted);
            }
            catch (Exception ex)
            {
                error += ex.ToString();
            }
        }
    }
0
 
LVL 12

Expert Comment

by:TheMegaLoser
Comment Utility
Cant see anything wrong with it although I know Gmail SMTP is very slow sometimes.

If you remove the

client.Send(mail);

Can you run your program ok then?
0
 

Author Comment

by:m-jansen
Comment Utility
No. It does not work when removing client.Send(mail); either. Same problem.
0
 

Author Comment

by:m-jansen
Comment Utility
But it works if I remove the Attachments code in the mail.
0
 

Author Comment

by:m-jansen
Comment Utility
Looks like this solved the problem:

MailMessage mail = new MailMessage();
            finally
            {
                mail.Dispose();
            }
0
 

Author Comment

by:m-jansen
Comment Utility
so I need to be carefull with using Dispose() when doing IO operations?
0
 
LVL 12

Expert Comment

by:TheMegaLoser
Comment Utility
You shouldn't have to be, it's probably a timing thing as TheLearnedOne suggested earlier.

The file probably stays open after it's added as an attachment until the mail object is destroyed. It probably lingers in the GC and keeps the file open which explains the locking. By disposing your forcing it into closing the file. If this assumption is correct I consider it a major design flaw though.

Glad you have it working :)
0
 

Author Comment

by:m-jansen
Comment Utility
From the VS help:
Call Dispose when you are finished using the ActivationContext. The Dispose method leaves the ActivationContext in an unusable state. After calling Dispose, you must release all references to the ActivationContext so the garbage collector can reclaim the memory that the ActivationContext was occupying. For more information, see Cleaning Up Unmanaged Resources and Implementing a Dispose Method.
Note: This method is new in the .NET Framework version 2.0.
0
 

Author Comment

by:m-jansen
Comment Utility
Thanks for helping me
0

Featured Post

6 Surprising Benefits of Threat Intelligence

All sorts of threat intelligence is available on the web. Intelligence you can learn from, and use to anticipate and prepare for future attacks.

Join & Write a Comment

Just a quick little trick I learned recently.  Now that I'm using jQuery with abandon in my asp.net applications, I have grown tired of the following syntax:      (CODE) I suppose it just offends my sense of decency to put inline VBScript on a…
It was really hard time for me to get the understanding of Delegates in C#. I went through many websites and articles but I found them very clumsy. After going through those sites, I noted down the points in a easy way so here I am sharing that unde…
It is a freely distributed piece of software for such tasks as photo retouching, image composition and image authoring. It works on many operating systems, in many languages.
Internet Business Fax to Email Made Easy - With eFax Corporate (http://www.enterprise.efax.com), you'll receive a dedicated online fax number, which is used the same way as a typical analog fax number. You'll receive secure faxes in your email, fr…

762 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

6 Experts available now in Live!

Get 1:1 Help Now