简体   繁体   English

如何避免异常进程无法访问该文件,因为它正由另一个进程使用。 在.net

[英]How to avoid exception The process cannot access the file because it is being used by another process. in .net

I am unzipping a.gz files by using the following code.Since i have huge number of files , I am using TPL tasks to run this code. 我使用以下代码解压缩a.gz文件。由于我有大量文件,我使用TPL任务来运行此代码。 But I used to get .NET exception: 但我曾经得到.NET异常:

The process cannot access the file because it is being used by another process. 该进程无法访问该文件,因为该文件正由另一个进程使用。

How to correct this issue? 如何解决这个问题?
Code used is as follows: 使用的代码如下:

private static void Decompress(FileInfo fileToDecompress)
{
    using (FileStream originalFileStream = fileToDecompress.OpenRead())
    {
        string currentFileName = fileToDecompress.FullName;
        string newFileName = currentFileName.Remove(currentFileName.Length - 
                                          fileToDecompress.Extension.Length);
        using (FileStream decompressedFileStream = File.Create(newFileName))
        {
            using (GZipStream decompressionStream = 
                     new GZipStream(originalFileStream, 
                                    CompressionMode.Decompress))
            {
                decompressionStream.CopyTo(decompressedFileStream);
            }
        }
    }
    //File.Move(myffile, Path.ChangeExtension(myffile, ".jpg"));
}

calling code is as shown below 调用代码如下所示

var list = ftp.GetFileList(remotepath);

//-------------------
DateTime dt = DateTime.Now;
string st = String.Format("{0:yyyyMMdd}", dt);//20161120
Task[] myTasks = new Task[list.Count];
int i = 0;
foreach (string item in list)
{
     if (item.StartsWith("GExport_") && (!item.ToUpper().Contains("DUM")) && (item.Contains(st)) && (!item.ToUpper().Contains("BLK")))
     {
         4gpath = item;
        //Downloadfile()   
        ftp.Get(dtr["REMOTE_FILE_PATH"].ToString() + 4gpath , @localDestnDir + "\\" + dtr["SOURCE_PATH"].ToString());
        download_location_hw = dtr["LOCAL_FILE_PATH"].ToString();
        // Spin off a background task to process the file we just downloaded
        myTasks[i++] = Task.Factory.StartNew(() =>
        {
            //Extractfile()             
            ExtractZipfiles(download_location_hw + "//" + huwawei4gpath, dtr["REMOTE_FILE_PATH"].ToString(), 
             dtr["FTP_SERVER"].ToString(), dtr["FTP_USER_ID"].ToString(),
             dtr["TECH_CODE"].ToString(), dtr["VENDOR_CODE"].ToString());
        }
    }
}

private static void ExtractZipfiles(string download_location_hw,string remotepath,string server,string userid,string tech,string vendor)
{
    if (download_location_hw.Contains(".gz"))
    {
        DirectoryInfo directorySelected = new DirectoryInfo(Path.GetDirectoryName(download_location_hw));
        foreach (FileInfo fileToDecompress in directorySelected.GetFiles("*.gz"))
        {
            Decompress(fileToDecompress);
        }
    }

}

You're possibly extracting the zip files downloaded bu your tasks in the same folder: 您可能在同一文件夹中解zip下载的zip文件:

download_location_hw = dtr["LOCAL_FILE_PATH"].ToString();
var directorySelected = new DirectoryInfo(Path.GetDirectoryName(download_location_hw));

If for somethat reason you have two files being targeted to the same local path, final foreach statement will have intersections with other tasks: 如果由于某些原因您将两个文件定位到同一本地路径,则最终的foreach语句将与其他任务交叉:

foreach (var fileToDecompress in directorySelected.GetFiles("*.gz"))
{
    Decompress(fileToDecompress);
}

Here you're searching for all *.gz files in folder, even those ones that can be still in download mode or being decompressed by other process. 在这里,您将搜索文件夹中的所有*.gz文件,甚至是那些仍处于下载模式或正在被其他进程解压缩的文件。 So you should be definitely sure each tasks is being run in the different folder. 因此,您应该确定每个任务都在不同的文件夹中运行。

If you want to simple correction of your code, you may try this (the main change here is not to enumerate all the archive files but simply get one from the task arguments, with FileInfo constructor ): 如果你想简单地修改你的代码,你可以试试这个(这里的主要变化不是枚举所有的归档文件,而只是从任务参数中获取一个,使用FileInfo构造函数 ):

private static void ExtractZipfiles(string download_location_hw,string remotepath,string server,string userid,string tech,string vendor)
{
    if (download_location_hw.Contains(".gz") && File.Exists(download_location_hw))
    {
        Decompress(new FileInfo(download_location_hw));
    }
}

The various tasks are operating on the same download path and are causing a collission. 各种任务在相同的下载路径上运行并导致冲突。 For eg. 例如。 Task 1 puts a.gz, b.gz while Task 2 puts c.gz under "MyDir". 任务1放置a.gz,b.gz,而任务2放置c.gz在“MyDir”下。

But now both tasks are operating and trying to rename the files to a, b, c during decompression. 但是现在这两个任务都在运行并尝试在解压缩期间将文件重命名为a,b,c So, it appears you need to create subdirectories for each of the tasks or prefix\\suffix the file names that are downloaded with unique identifiers. 因此,您似乎需要为每个任务创建子目录,或者使用唯一标识符前缀\\ suffix下载的文件名。

暂无
暂无

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

相关问题 System.IO异常“该进程无法访问该文件,因为该文件正在被另一个进程使用。” - System.IO exception “The process cannot access the file 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.' ” 该进程无法访问文件“文件名”,因为它正在被另一个进程使用。 并且拒绝访问路径“文件名” - the process cannot access the file 'filename' because it is being used by another process. and Access to the path 'filename' is denied 该进程无法访问该文件,因为它正在被另一个进程使用。 文件复制 - The process cannot access the file because it is being used by another process. File.Copy System.IO.IOException: '进程无法访问文件“文件位置”,因为它正被另一个进程使用。 - System.IO.IOException: 'The process cannot access the file "file location"because it is being used by another process.' email 删除附件文件后,错误“该进程无法访问该文件,因为它正在被另一个进程使用。” - after email deleting attachment file, error “The process cannot access the file because it is being used by another process.” 该进程无法访问该文件,因为该文件正在被另一个进程使用。 File.Create方法 - The process cannot access the file because it is being used by another process. File.Create method 为什么收到“该进程无法访问该文件,因为该文件正在被另一个进程使用。” - Why am i receiving a “The process cannot access the file because it is being used by another process.” “该进程无法访问该文件,因为它正被另一个进程使用。” 使用 SystemReader - “The process cannot access the file because it is being used by another process.” with SystemReader 收到错误消息“该进程无法访问该文件,因为该文件正在被另一个进程使用。” - Getting an error 'The process cannot access the file because it is being used by another process.'
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM