文件正在被另一个进程使用 [英] File is being used by another process

查看:253
本文介绍了文件正在被另一个进程使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好,

要发送通话详细信息,我正在尝试使用以下代码:

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);
            }


第一次才运作良好.但是下一次它抛出一个例外,即该文件正在被另一个进程使用.但是,发送邮件后,该文件应该可以在应用程序中供多用户使用.我不确定现在该怎么办.

问候!
Aman


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

推荐答案

正在发生的事情是您的代码中的某些元素(可能是Attachment或MailMessage,但可能是SmtpClient)未正确处理.一个猜测(因为我们看不到代码片段的整个范围),它超出范围并消失了.如果发生这种情况,并且文件引用未关闭,则取决于处理时发生的垃圾收集器-直到那时,该文件仍在使用中"并且不可用于其他进程.可能是现在,也可能是下周-这已超出您的控制范围.

在使用完资源后,尝试在资源上调用Dispose(无论如何是一种好习惯),将它们包含在using块中,这将为您完成.


亲爱的OriginalGriff,您可以看到我正在使用File类.如何使用相同的类或不使用FileStream或File来关闭文件"


您正在使用File类创建文件,但这可能不是问题(可以通过删除File代码进行测试,确保文件存在并查看问题是否消失-我怀疑不会).可能是保存文件的邮件附件代码-需要读取它才能发送文件.

如果它是文件代码,则使用FileStream手动创建它-完成后将其处置.

否则,请处置各种消息组件-无论如何都是这样做的好习惯!

亲爱的OriginalGriff,感谢您的支持.您可以看到我正在使用File类.如何使用相同的类或不使用FileStream或FileInfo来关闭文件?(仅供参考)"

您很快就知道了!我正在回应上一个!

很高兴听到它的效果.如果您在File或FileStream上使用Close方法,那么理论上无论如何都应该释放该文件,但是无论如何都要使用Dispose(就像任何系统资源一样,File处理-File和FileStream可以处理)是一个非常好的主意.包装-是稀缺资源,应尽快释放以用于其他用途.

最好的方法是using块:
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


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();
    }
}



希望这段代码对您有所帮助.

[edit]已将在线代码转换为代码块-OriginalGriff [/edit]



Hope this code will help you.

[edit]In line code converted to code block - OriginalGriff[/edit]


这篇关于文件正在被另一个进程使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆