c# Detect if file has finished being written

后端 未结 1 1336
长发绾君心
长发绾君心 2021-02-10 08:17

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(exportN         


        
1条回答
  •  误落风尘
    2021-02-10 08:58

    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
    
        }
    
        /// 
        /// Code by ChrisW -> http://stackoverflow.com/questions/876473/is-there-a-way-to-check-if-a-file-is-in-use
        /// 
        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;
        }
    

    0 讨论(0)
提交回复
热议问题