簡體   English   中英

將文件寫入 .NET Core 中的臨時文件夾后無法讀取文件

[英]Can't read file after writing it to temp folder in .NET Core

在我的場景中,我有一個用例,我必須接收一個壓縮文件,進行一些驗證,然后在存檔中找到一個我必須通過第三方庫處理的特定文件。 不過,我在讓這樣的庫讀取文件時遇到了一些麻煩。 這是我到目前為止想出的:

public async Task ShapeIt(ZipArchive archive)
{
    foreach (var entry in archive.Entries)
    {
        if (Path.GetExtension(entry.FullName).Equals(".shp"))
        {
            var stream = entry.Open();
            using var ms = new MemoryStream();
            await stream.CopyToAsync(ms);
            ms.Position = 0;
            var fileName = Path.GetTempFileName();
            try
            {
                using var fileStream = File.Open(fileName, FileMode.OpenOrCreate, FileAccess.Write, 
                    FileShare.ReadWrite);

                var bytes = new byte[ms.Length];
                ms.Read(bytes, 0, (int)ms.Length);
                fileStream.Write(bytes, 0, bytes.Length);
                fileStream.Flush();
                fileStream.Close();

                var featureSource = new ShapeFileFeatureSource(fileName); // Class from 3rd-party
                featureSource.Open();
                // Do my stuff with the shapefile
            }
            finally
            {
                File.Delete(fileName);
            }
        }
    }
}

請注意,我正在使用復制流的“舊方法”,因為Stream.CopyToStream.CopyToAsync正在創建空文件,顯式調用fileStream.Close()看起來像是以某種方式將字節放入文件的唯一方法,但是這超出了我的意思。 無論如何,在關閉流后,調用featureSource.Open()我的應用程序拋出

"The process cannot access the file 'C:\\Users\\me\\AppData\\Local\\Temp\\tmpE926.tmp' because it is
being used by another process."

tmpE926.tmp都不同,很明顯。 還要注意,我正在創建一個文件,因為ShapeFileFeatureSource的構造函數需要的不是流,也不是字節數組,而是路徑。

一個更短的實現

public async Task ShapeIt(ZipArchive archive)
{
    foreach (var entry in archive.Entries)
    {
        var tempFile = Path.GetTempFileName();
        try
        {
            entry.ExtractToFile(tempFile, true);

            if (Path.GetExtension(entry.FullName).Equals(".shp"))
            {
                var featureSource = new ShapeFileFeatureSource(tempFile);
                featureSource.Open();
                var type = featureSource.GetShapeFileType();
            }
        }
        finally
        {
            File.Delete(tempFile);
        }
    }
}

實際上會導致相同的錯誤。 老實說,我不認為問題出在這個庫中,而是我以某種方式把它搞砸了。 有沒有人有任何想法,或者我應該聯系供應商的(沒有響應的)技術支持嗎?

編輯:以防萬一,這是這樣的庫Install-Package ThinkGeo.UI.WebApi但你必須訂閱評估才能使用它。

我找不到帶有此類類的 .NET Core 包,因此我通過 .NET Framework Nuget 包復制了它。 我的回答主要展示了如何處理流。 如果無法訪問您擁有的庫,就很難判斷您的代碼有什么問題

using DotSpatial.Data;
using System.IO;
using System.IO.Compression;

namespace ConsoleApp12
{
    class Program
    {
        static void Main(string[] args)
        {
            using (var fs = File.OpenRead(@"C:\Users\jjjjjjjjjjjj\Downloads\1270055001_mb_2011_vic_shape.zip"))
            using (var zipFile = new ZipArchive(fs))
            {
                foreach (var entry in zipFile.Entries)
                {
                    if (entry.FullName.EndsWith(".shp"))
                    {
                        var tempFile = Path.GetTempFileName();
                        try
                        {
                            using (var entryStream = entry.Open())
                            using (var newFileStream = File.OpenWrite(tempFile))
                            {
                                entryStream.CopyTo(newFileStream);
                            }
                            var featureSource = ShapefileFeatureSource.Open(tempFile);
                            var type = featureSource.ShapeType;
                        }
                        finally
                        {
                            File.Delete(tempFile);
                        }
                    }
                }
            }
        }
    }
}

UPD:安裝了 ThinkGeo 庫的試用版,而不是未經授權的異常,它給我FileNotFoundException和給定的堆棧跟蹤

at ThinkGeo.Core.ValidatorHelper.CheckFileIsExist(String pathFilename)
at ThinkGeo.Core.ShapeFileIndex.xh8=(FileAccess readWriteMode)
^^^^^^^^^^^^^^^^^^^^^^^^^ Are we supposed to have index?
at ThinkGeo.Core.ShapeFile.xh8=(FileAccess readWriteMode)
at ThinkGeo.Core.ShapeFileFeatureSource.WjE=()
at ThinkGeo.Core.ShapeFileFeatureSource.OpenCore()
at ThinkGeo.Core.FeatureSource.Open()
at ConsoleApp20.Program.Main(String[] args) in 
C:\Users\jjjjjjjjjjjj\source\repos\ConsoleApp20\ConsoleApp20\Program.cs:line 45

ShapeFileIndex ? 所以我想我應該以這種方式深入研究

var featureSource = new ShapeFileFeatureSource(tempFile);
featureSource.RequireIndex = false; // no luck
featureSource.Open();

我試圖找到它想要的 idx 文件的任何引用,它具有屬性IndexFilePathName ,但不幸的是,我運氣不好。 (也試過不同的文件夾,所以它不是“臨時”文件夾問題) 在此處輸入圖片說明

這段代碼修改了幾天,直到我聯系了技術支持,他們對它進行了一些修改並想出了這個:

public async Task ProcessFile(IFormFile file)
{
    if (!Path.GetExtension(file.FileName).Equals(".zip"))
        throw new System.Exception("File should be compressed in '.zip' format");

    var filePaths = new List<string>();

    using (var stream = new MemoryStream())
    {
        await file.CopyToAsync(stream);

        using (var archive = new ZipArchive(stream, ZipArchiveMode.Read, false))
        {

            var replaceList = new Dictionary<string, string>();

            foreach (ZipArchiveEntry entry in archive.Entries)
            {
                var tempPath = Path.GetTempFileName();

                string key = Path.GetFileNameWithoutExtension(entry.FullName);

                string value = Path.GetFileNameWithoutExtension(tempPath);

                if (replaceList.ContainsKey(key))
                {
                    value = replaceList[key];
                }
                else
                {
                    replaceList.Add(key, value);
                }

                string unzippedPath = Path.Combine(Path.GetDirectoryName(tempPath), value + Path.GetExtension(entry.FullName));

                entry.ExtractToFile(unzippedPath, true);
                filePaths.Add(unzippedPath);
            }

            foreach (var unzippedPath in filePaths)
            {
                if (Path.GetExtension(unzippedPath).Equals(".shp"))
                {
                    // Successfully doing third-party library stuff
                }
            }

            foreach (var unzippedPath in filePaths)
            {
                if (File.Exists(unzippedPath))
                {
                    File.Delete(unzippedPath);
                }
            }
        }
    }
}

有用。 我很高興。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM