Click here to Skip to main content
15,888,351 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi All,

To send call details I am trying following code:
try
{
               path = HttpRuntime.AppDomainAppPath+"/Calls Reports.xls";                
               if (!File.Exists(path))
                {
                    File.Create(path);
                }
               using (StringWriter sw = new StringWriter())
                {
                    using (HtmlTextWriter htw = new HtmlTextWriter(sw))
                    {
                        DataGrid dg = new DataGrid();
                        dg.DataSource = ds.Tables[0];
                        dg.DataBind();
                        dg.RenderControl(htw);
                        File.WriteAllText(path, sw.ToString());
                        htw.Close();
                        htw.Dispose();
                    }
                    sw.Close();
                    sw.Dispose();
                }
                Body = "The pending call detail of " + DateTime.Now.ToString("dd/MM/yyyy") + " is enclosed herewith as an attachment.";
                MailMessage MyMM = new MailMessage("from@gmail.com", "to@gmail.com", "Calls Report", Body);
                Attachment MyAttachment = new Attachment(path);
                MyMM.Attachments.Add(MyAttachment);
                MyMM.IsBodyHtml = true;
                SmtpClient MySC = new SmtpClient("smtp.gmail.com", 587);
                MySC.EnableSsl = true;
                MySC.Send(MyMM);
}
catch (Exception ex)
            {
                Body = "An exception occured while sending pending call detail of " + DateTime.Now.ToString("dd/MM/yyyy") + " i.e. " + ex.ToString();
                MailMessage MyMM = new MailMessage("from@gmail.com", "to@gmail.com", "Error at calls report", Body);                
                MyMM.IsBodyHtml = true;
                SmtpClient MySC = new SmtpClient("smtp.gmail.com", 587);
                MySC.EnableSsl = true;
                MySC.Send(MyMM);
            }

Which is working well only first time. But next time it throw the exception that file is being used by another process. However this file should accessable in application to mulitple user after sending mail. I m not sure what to do now.

Regards!
Aman
Posted
Updated 29-Dec-10 20:14pm
v3
Comments
Aman4.net 30-Dec-10 2:14am    
This code is written in class file!
OriginalGriff 30-Dec-10 3:22am    
Answer updated
OriginalGriff 30-Dec-10 3:29am    
Answer updated again!

What is happening is that some element of your code (probably the Attachment or MailMessage, but possibly the SmtpClient) is not disposed properly. At a guess (because we can't see the whole scope of the code fragment), it is going out of scope and disappearing. If this happens, and the file references are not closed, then it is up to the garbage collector when the dispose happens - until then, the file is still "in use" and not available to other processes. This could be now, or next week - it is out of your control.

Try either calling Dispose on your resources when you have finished with them (it's good practice anyway) of enclose them in a using block which will do it for you.


"Dear OriginalGriff, As you can see I am using File class. How can i close the file using same class or without using FileStream or File"


You are using the File class to create the file, but that may not be the problem (You could test by removing the File code, ensuring the file exists and see if the problem disappears - I suspect it won't) . It may be the mail attachment code that is holding the file - it needs to read it in order to send it.

If it is the File code, then manually create it using the FileStream - and dispose it when you are done.

Otherwise, dispose the various message components - it's good practice to do that anyway!

"Dear OriginalGriff, Thanx it works. As you can see I am using File class. How can i close the file using same class or without using FileStream or FileInfo?(Just for knowledge)"

You got that in quick! I was responding to the previous one!

Glad to hear it works. Provided you use the Close method on the File, or FileStream, then in theory the file should be released anyway, but it is a very good idea to use Dispose anyway (just as for any system resource, File handles - which the File and FileStream wrap - are scarce resources and should be released ASAP to allow other uses).

The best way is a using block:
using (StreamWriter sw = new StreamWriter(@"C:\Temp\Temp.txt"))
   {

   ... // Use sw here

   } // sw goes out of scope here, and is disposed automatically
 
Share this answer
 
v3
Comments
Aman4.net 30-Dec-10 3:18am    
Dear OriginalGriff, Thanx it works. As you can see I am using File class. How can i close the file using same class or without using FileStream or FileInfo?(Just for knowledge)
Rajesh Anuhya 30-Dec-10 3:25am    
Good answer
Aman4.net 30-Dec-10 4:51am    
Dear OriginalGriff, Thanx for giving such good answer!
public class OpenTest 
{
    public static void Main() 
    {
        // Open an existing file, or create a new one.
        FileInfo fi = new FileInfo("temp.txt");

        // Open the file just specified such that no one else can use it.
        FileStream fs = fi.Open( FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None );

        // Create another reference to the same file.
        FileInfo nextfi = new FileInfo("temp.txt");        

        try 
        {
            // Try opening the same file, which was locked by the previous process.
            nextfi.Open( FileMode.OpenOrCreate, FileAccess.Read );

            Console.WriteLine("The file was not locked, and was opened by a second process.");
        } 
        catch (IOException) 
        {
            Console.WriteLine("The file could not be opened because it was locked by another process.");
        } 
        catch (Exception e) 
        {
            Console.WriteLine(e.ToString());
        }

        // Close the file so it can be deleted.
        fs.Close();
    }
}


Hope this code will help you.

[edit]In line code converted to code block - OriginalGriff[/edit]
 
Share this answer
 
v2
Comments
OriginalGriff 30-Dec-10 12:00pm    
I converted your in line code to a code block. (Use pre tags instead of code tags)
This preserves the formatting and applies a highlight which makes the code easier to read.
fjdiewornncalwe 30-Dec-10 12:50pm    
My vote of 1: The question was already thoroughly answered and marked by the OP as correct. Your answer didn't add anything new that wasn't covered by Griff, so it didn't need to get posted.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900