问题
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