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"))
{
...
}