Cannot access

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.....
m-jansenAsked:
Who is Participating?
 
TheMegaLoserConnect With a Mentor Commented:
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
 
m-jansenAuthor Commented:
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
 
Bob LearnedCommented:
Are you closing the FileStream after you use it?  What is the timing of things?

Bob
0
Free Tool: ZipGrep

ZipGrep is a utility that can list and search zip (.war, .ear, .jar, etc) archives for text patterns, without the need to extract the archive's contents.

One of a set of tools we're offering as a way to say thank you for being a part of the community.

 
Maher-JendasiCommented:
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
 
m-jansenAuthor Commented:
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
 
m-jansenAuthor Commented:
Maher-Jendasi: What should I filer out to see what I need to see with RegMon?
0
 
m-jansenAuthor Commented:
TheLearnedOne: What about the timing? How to debug this?
0
 
Bob LearnedConnect With a Mentor Commented:
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
 
m-jansenAuthor Commented:
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
 
Bob LearnedCommented:
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
 
m-jansenAuthor Commented:
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
 
Bob LearnedCommented:
Is it included as part of the solution?  Or is it just shown when you have "Show All Files"?

Bob
0
 
m-jansenAuthor Commented:
It is showed in "Nest related files"
0
 
m-jansenAuthor Commented:
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
 
m-jansenAuthor Commented:
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
 
m-jansenAuthor Commented:
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
 
m-jansenAuthor Commented:
I get the error on this line

objFileStream = new FileStream(Server.MapPath(fName), FileMode.Create, FileAccess.ReadWrite);
0
 
m-jansenAuthor Commented:
After choosing Build -> Rebuild Solution it was possible to delete the file again..... strange things.
0
 
m-jansenAuthor Commented:
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
 
m-jansenAuthor Commented:
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
 
m-jansenAuthor Commented:
It did not make any difference to remove the Global.asax
0
 
m-jansenAuthor Commented:
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
 
m-jansenAuthor Commented:
Does anyone follow me? Or should I make a new and better question?
0
 
Bob LearnedCommented:
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
 
m-jansenAuthor Commented:
>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
 
m-jansenAuthor Commented:
writing values into a .csv file is what I do
0
 
TheMegaLoserCommented:
Are you creating multiple instances of the object?
0
 
m-jansenAuthor Commented:
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
 
m-jansenAuthor Commented:
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
 
TheMegaLoserCommented:
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
 
m-jansenAuthor Commented:
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
 
TheMegaLoserCommented:
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
 
m-jansenAuthor Commented:
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
 
m-jansenAuthor Commented:
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
 
m-jansenAuthor Commented:
The code stops here in my SendMail() on the second run.

Attachment data = new Attachment(Server.MapPath(file), MediaTypeNames.Application.Octet);
0
 
m-jansenAuthor Commented:
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
 
m-jansenAuthor Commented:
I have not moved the colse statements yet...
0
 
m-jansenAuthor Commented:
what does finally clause means?
0
 
m-jansenAuthor Commented:
and where to place it
0
 
m-jansenAuthor Commented:
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
 
m-jansenAuthor Commented:
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
 
m-jansenAuthor Commented:
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
 
TheMegaLoserCommented:
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
 
m-jansenAuthor Commented:
No. It does not work when removing client.Send(mail); either. Same problem.
0
 
m-jansenAuthor Commented:
But it works if I remove the Attachments code in the mail.
0
 
m-jansenAuthor Commented:
Looks like this solved the problem:

MailMessage mail = new MailMessage();
            finally
            {
                mail.Dispose();
            }
0
 
m-jansenAuthor Commented:
so I need to be carefull with using Dispose() when doing IO operations?
0
 
TheMegaLoserCommented:
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
 
m-jansenAuthor Commented:
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
 
m-jansenAuthor Commented:
Thanks for helping me
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.