简体   繁体   English

Windows 服务文件流给出 System.IO.IOException:进程无法访问文件“文件名”,因为它正被另一个进程使用

[英]Windows Service Filestream giving System.IO.IOException: The process cannot access the file "filename" because it is being used by another process

I've got a windows service that I have to modify.我有一个必须修改的 windows 服务。 Current code is this:当前代码是这样的:

 public IRecord2 GetRecord(string name)
 {
      string path = Path.Combine(this.DirectoryPath, name);
      if (!File.Exists(path))
          return null;
      byte[] contents;
      lock (locker)   {
            using(FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite, bufferSize:4096, useAsync:true)) //WHERE THE PROBLEM IS OCCURRING
            {
                using (BinaryReader br = new BinaryReader(fs))
                {
                    contents = br.ReadBytes((int)fs.Length);
                    br.Close(); //unnecessary but threw it in just to be sure
                    fs.Close(); //unnecessary but threw it in just to be sure
                }
            }
            
        }
     return new Record2()
        {
            Name = name,
            Contents = contents
        };
}

Code that calls the function:调用 function 的代码:

 public void Process(string pickupFileName)
    {
        string uniqueId = DateTime.Now.ToString("(yyyy-MM-dd_HH-mm-ss)");
        string exportFileName = Path.GetFileNameWithoutExtension(pickupFileName) + "_" + uniqueId + ".csv";
        string archiveFileName = Path.GetFileNameWithoutExtension(pickupFileName) + "_" + uniqueId + Path.GetExtension(pickupFileName);
        string unprocessedFileName = Path.GetFileNameWithoutExtension(pickupFileName) + "_" + uniqueId + Path.GetExtension(pickupFileName);

        try
        {
            _logger.LogInfo(String.Format("Processing lockbox file '{0}'", pickupFileName));

            IRecord2 record = _pickup.GetRecord(pickupFileName);
            if (record == null)
                return;

            _archive.AddOrUpdate(new Record2() { Name = archiveFileName, Contents = record.Contents });

            string pickupFileContents = UTF8Encoding.UTF8.GetString(record.Contents);

            IBai2Document document = Bai2Document.CreateFromString(pickupFileContents);
            StringBuilder sb = Export(document);

            _export.AddOrUpdate(new Record2() { Name = exportFileName, Contents = Encoding.ASCII.GetBytes(sb.ToString()) });

            _pickup.Delete(pickupFileName);
        }
        catch(Exception ex)
        {
            throw ex;
        }
    }

Function that calls Process:调用Process的Function:

public void Process()
    {
        foreach (ConfigFolderPath configFolderPath in _configSettings.ConfigFolderPaths)
        {
            IRecordRepository pickup = new FileRepository(configFolderPath.PickupFolderPath);
            IRecordRepository export = new FileRepository(configFolderPath.ExportFolderPath);
            IRecordRepository archive = new FileRepository(configFolderPath.ArchiveFolderPath);
            IRecordRepository unprocessed = new FileRepository(configFolderPath.UnprocessedFolderPath);

            Converter converter = new Converter(Logger,pickup, export, archive, unprocessed);
            
            foreach (string fileName in pickup.GetNames())
            {
                if (_configSettings.SupportedFileExtensions.Count > 0 && !_configSettings.SupportedFileExtensions.Any(extension => extension.ToLower() == Path.GetExtension(fileName).ToLower()))
                    continue;

                Action action = () => converter.Process(fileName);
                _queue.TryEnqueue(action, new WorkTicket() { Description = String.Format("Processing '{0}'", fileName), SequentialExecutionGroup = fileName });
            }
        }
    }

When 1 file is sent to the service, it processes and reads the file correctly.当 1 个文件发送到服务时,它会正确处理和读取文件。 However, if two files are sent (difference of 3 minutes), the first file will process correctly, but the second will give me "System.IO.IOException: The process cannot access the file "filename" because it is being used by another process.但是,如果发送两个文件(相差 3 分钟),第一个文件将正确处理,但第二个文件会给我“System.IO.IOException: The process cannot access the file "filename" because it is being used by another过程。

Is the solution to use a mutex as per https://stackoverflow.com/a/29941548/4263285 or is there a better solution to solve this?是按照https://stackoverflow.com/a/29941548/4263285使用互斥锁的解决方案还是有更好的解决方案来解决这个问题?

Edit: More context:编辑:更多上下文:

Service is constantly running - as soon as files are dropped into a folder, it begins the process.服务一直在运行 - 一旦文件被放入文件夹,它就会开始该过程。

  1. get the file data (function up above)获取文件数据(上面的函数)
  2. take the data, transform it, and put it into a different file获取数据,对其进行转换,然后将其放入不同的文件中
  3. Delete the original file from the one up above从上面的文件中删除原始文件

rinse and repeat if more files如果有更多文件,请冲洗并重复

if one file is placed in the folder, it works correctly.如果将一个文件放在文件夹中,则它可以正常工作。 if two files are placed in the folder, it breaks on the second file if service is stopped and restarted, it works again如果将两个文件放在文件夹中,它会在第二个文件上中断如果服务停止并重新启动,它会再次工作

In your code add ".Close()" here, at the end of the line:在您的代码中,在行尾添加“.Close()”:

using(FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite, bufferSize:4096, useAsync:true).Close())

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 System.IO.IOException: '进程无法访问文件“文件位置”,因为它正被另一个进程使用。 - System.IO.IOException: 'The process cannot access the file "file location"because it is being used by another process.' System.IO.IOException: '进程无法访问文件 '@.txt',因为它正被另一个进程使用。 - System.IO.IOException: 'The process cannot access the file '@.txt' because it is being used by another process.' 类型为“ System.IO.IOException”的未处理异常。该进程无法访问该文件,因为该文件正在被另一个进程使用 - An unhandled exception of type 'System.IO.IOException'.The process cannot access the file because it is being used by another process System.IO.IOException:进程无法访问文件“somefile.txt”,因为它正被另一个进程使用 - System.IO.IOException: The process cannot access the file 'somefile.txt' because it is being used by another process System.IO.IOException:进程无法访问文件'.txt',因为它正由另一个进程使用 - System.IO.IOException: The process cannot access the file '.txt' because it is being used by another process 错误:帮助D:System.IO.IOException:该进程无法访问文件,因为它正在被另一个进程使用 - Error: Help D: System.IO.IOException: The process cannot access the file because it is being used by another process System.IO.IOException: '进程无法访问该文件,因为它正被另一个进程使用 - System.IO.IOException: 'The process cannot access the file because it is being used by another process “ System.IO.IOException:该进程无法访问文件'C:\\ Test \\ test.txt',因为它正在被另一个进程使用” - “System.IO.IOException: The process cannot access the file 'C:\Test\test.txt' because it is being used by another process” ZipFile.CreateFromDirectory 抛出 System.IO.IOException:进程无法访问文件 X,因为它正被另一个进程使用 - ZipFile.CreateFromDirectory throws System.IO.IOException : The process cannot access the file X because it is being used by another process 此代码给出此异常“System.IO.IOException:'该进程无法访问该文件,因为它正在被另一个进程使用。” ” - this code give this exception “System.IO.IOException: 'The process cannot access the file because it is being used by another process.' ”
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM