我在按钮点击事件中有这个代码:
private void button1_Click(object sender, EventArgs e)
{
WatchDirectory();
StreamWriter w = new StreamWriter(userVideosDirectory + "\\UploadedVideoFiles.txt",true);
w.WriteLine(fileforupload);
w.Close();
uploadedFilesList.Add(fileforupload);
Youtube_Uploader youtubeupload = new Youtube_Uploader(uploadedFilesList[0]);
}
现在我要做的是WatchDirectory在这个方法中,一旦文件没有被锁定而没有使用,我会看一个文件,然后继续按下按钮点击事件。
不知怎的,我需要在调用WatchDirectory时进行while循环或者某些事情,当文件不再被锁定时,继续执行其余的代码:
按钮单击中的此代码仅在文件未被锁定/正在使用时才执行此操作:
StreamWriter w = new StreamWriter(userVideosDirectory + "\\UploadedVideoFiles.txt",true);
w.WriteLine(fileforupload);
w.Close();
uploadedFilesList.Add(fileforupload);
Youtube_Uploader youtubeupload = new Youtube_Uploader(uploadedFilesList[0]);
这是WatchDirectory方法:
FileSystemWatcher watcher;
private void WatchDirectory()
{
watcher = new FileSystemWatcher();
watcher.Path = userVideosDirectory;
watcher.NotifyFilter = NotifyFilters.LastWrite | NotifyFilters.Size;
watcher.Filter = "*.mp4";
watcher.Changed += new FileSystemEventHandler(OnChanged);
watcher.EnableRaisingEvents = true;
}
private void OnChanged(object source, FileSystemEventArgs e)
{
var info = new FileInfo(e.FullPath);
fileforupload = info.FullName;
if (IsFileLocked(fileforupload) == false)
{
watcher.EnableRaisingEvents = false;
watcher.EnableRaisingEvents = true;
}
}
IsFileLocked方法。
public bool IsFileLocked(string filename)
{
bool Locked = false;
try
{
FileStream fs = File.Open(filename, FileMode.OpenOrCreate,
FileAccess.ReadWrite, FileShare.None);
fs.Close();
}
catch (IOException ex)
{
Locked = true;
}
return Locked;
}
逻辑应该是这样的:
调用WatchDirectory然后观看文件:
File is locked
File is locked
File is locked
File is locked
File is not locked and not in use
Now do the rest of the code in the button click event
当它检查文件已锁定或未启用false时,按钮1一旦未锁定就会启用它。