当然,有许多问题与我的相似,但是没有一个问题能真正回答我的问题,也没有提出为什么它能在调试中而不是在运行时运行的问题。
我做了一个FileSystemWatcher
等待在我的服务器上的目录中创建一个文件。引发一个Event
,然后选择引起它的文件名,将其复制为另一个目录.csv
。当一步一步调试时,当我编译时一切正常,尝试中断File.copy()
。
class Program
{
public static string AdresaEXD { get; set; }
public static string AdresaCSV { get; set; }
public static string IzvorniFajl { get; set; } //source file
public static string KreiraniFajl { get; set; }// renamed file
static void Main(string[] args)
{
GledanjeFoldera();/ watcher
}
static void GledanjeFoldera()
{
AdresaEXD = @"H:\CRT_FOR_FIS\EXD";
AdresaCSV = @"H:\CRT_FOR_FIS\CSV";
FileSystemWatcher CRT_gledaj = new FileSystemWatcher(AdresaEXD,"*.exd");
// Making filters
CRT_gledaj.NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite | NotifyFilters.DirectoryName | NotifyFilters.FileName;
// create event handler
CRT_gledaj.Created += new FileSystemEventHandler(ObradaITransformacijaEXD);
// starting to watch
CRT_gledaj.EnableRaisingEvents = true;
// loop
Console.WriteLine("Ako zelite da prekinete program pritisnite \'q\'.");
while (Console.ReadLine() != "q");
}
private static void ObradaITransformacijaEXD(object source, FileSystemEventArgs e) //
{
//
string NoviFajl = e.Name.Remove(e.Name.Length-4,4)+".csv";// new file name
// create paths
IzvorniFajl = System.IO.Path.Combine(AdresaEXD, e.Name);
KreiraniFajl = System.IO.Path.Combine(AdresaCSV, e.Name);
// copy file to other destination and delete after
System.IO.File.Copy(IzvorniFajl, KreiraniFajl, true);
System.IO.File.Delete(IzvorniFajl);
}
}
问题在于,开始创建文件时会触发FileSystemWatcher事件。请尝试以下方法:
private static 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;
}
如果正在使用文件,则此函数返回true。所以你可以做一个这样的循环
while (IsFileLocked(new FileInfo(eventArgs.FullPath))) { }
然后等待退出循环以复制文件
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句