c# Detect if file has finished being written

[亡魂溺海] 提交于 2019-12-05 02:38:10

问题


I am writing a PowerPoint add-in that FTPs a file that has been converted to a WMV.

I have the following code which works fine:

oPres.CreateVideo(exportName);
oPres.SaveAs(String.Format(exportPath, exportName),PowerPoint.PpSaveAsFileType.ppSaveAsWMV,MsoTriState.msoCTrue);

But this kicks off a process within PP which does the file conversion and it immediately goes to the next line of code before the file has finished being written.

Is there a way to detect when this file has finished being written so I can run the next line of code knowing that the file has been finished?


回答1:


When a file is being used it is unavailable, so you could check the availability and wait until the file is available for use. An example:

    void AwaitFile()
    {
        //Your File
        var file  = new FileInfo("yourFile");

        //While File is not accesable because of writing process
        while (IsFileLocked(file)) { }

        //File is available here

    }

    /// <summary>
    /// Code by ChrisW -> http://stackoverflow.com/questions/876473/is-there-a-way-to-check-if-a-file-is-in-use
    /// </summary>
    protected virtual bool IsFileLocked(FileInfo file)
    {
        FileStream stream = null;

        try
        {
            stream = file.Open(FileMode.Open, FileAccess.ReadWrite, FileShare.None);
        }
        catch (IOException)
        {
            return true;
        }
        finally
        {
            if (stream != null)
                stream.Close();
        }

        //file is not locked
        return false;
    }


来源:https://stackoverflow.com/questions/17612800/c-sharp-detect-if-file-has-finished-being-written

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!