我有一个Windows服务,该服务监视目录中是否有新文件,并且在将文件创建/复制到该目录时,它将重命名该文件并进行一些处理。
我正在使用File.Move重命名文件。
当我从控制台应用程序中使用完全相同的代码但现在作为Windows服务运行时,它可以正常工作。
用于初始化文件监视程序的代码
public void StartFileSystemWatcher()
{
listFileSystemWatcher = new List<FileSystemWatcher>();
foreach (var customFolder in listFolders)
{
var dir = new DirectoryInfo(customFolder.FolderPath);
if (customFolder.FolderEnabled && dir.Exists)
{
var fileSWatch = new FileSystemWatcher
{
Filter = customFolder.FolderFilter,
Path = customFolder.FolderPath,
NotifyFilter = NotifyFilters.LastWrite | NotifyFilters.FileName | NotifyFilters.DirectoryName,
EnableRaisingEvents = true
};
fileSWatch.Created += (senderObj, fileSysArgs) => FileSWatch_Created(senderObj, fileSysArgs, customFolder.VSTSUrl);
listFileSystemWatcher.Add(fileSWatch);
logger.Info(string.Format("Starting to monitor files with extension ({0}) in the folder ({1})", fileSWatch.Filter, fileSWatch.Path));
}
else
{
logger.Info(string.Format("File system monitor cannot start because the folder ({0}) does not exist", customFolder.FolderPath));
}
}
}
private void FileSWatch_Created(object sender, FileSystemEventArgs e, string vstsUrl)
{
PostFileInfoToVSTS(e.FullPath, vstsUrl);
}
创建文件时运行的代码
private void PostFileInfoToVSTS(string filePath, string vstsUrl)
{
try
{
var fileName = filePath.Substring(filePath.LastIndexOf("\\") + 1);
var fileParts = fileName.Split(new char[] { '.' });
if (fileParts.Length == 6)
{
//rename the file
var fileNewName = $"{fileParts[2]}.{fileParts[3]}.{fileParts[4]}.TXT";
var fileNewPath = $"{Path.GetDirectoryName(filePath)}\\oldfiles\\{fileNewName}";
File.Move(filePath, fileNewPath);
//prepare vsts request
var request = new VSTSRequest();
request.Variables.Region.Value = fileParts[0];
request.Variables.Sparc.Value = fileParts[1];
request.Variables.SystemName.Value = fileParts[2];
request.Variables.Type.Value = fileParts[3];
request.Variables.Name.Value = fileParts[4];
request.Variables.Filename.Value = fileNewName;
var httpWebRequest = (HttpWebRequest)WebRequest.Create(vstsUrl);
httpWebRequest.ContentType = "application/json";
httpWebRequest.Method = "POST";
httpWebRequest.Headers.Add("Authorization", ConfigurationManager.AppSettings["VSTSAuthentication"]);
//post to vsts
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
streamWriter.Write(JsonConvert.SerializeObject(request));
streamWriter.Flush();
streamWriter.Close();
}
//read response
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var result = streamReader.ReadToEnd();
var json = JsonConvert.DeserializeObject<dynamic>(result);
logger.Info($"File '{fileNewPath}' processed. ReleaseId: {json.id}.");
}
}
else
{
logger.Info($"File '{fileName}' wasn't processed. Name is not in the correct format.");
}
}
catch (Exception ex)
{
logger.Error(ex);
}
}
我第一次将文件复制到该目录中时,它可以正常工作,但是接下来,我得到了System.IO.IOException:该进程无法访问该文件,因为该文件正在被另一个进程使用。