簡體   English   中英

在文件流或字節數組中更改文件的名稱以通過 WebAPI 發送

[英]Changing the name of a file while in a filestream or byte array to send via WebAPI

我想在 memory 中獲取文件的內容並重命名文件,以便使用 API 以不同的文件名發送。

目標:

  1. 不得以任何方式更改原始文件(磁盤上的文件)。
  2. 不創建其他文件(例如具有新名稱的文件副本)。 我試圖讓 IO 訪問盡可能低,並在 memory 中執行所有操作。
  3. 將文件 object(在內存中)的名稱更改為其他名稱。
  4. 將文件 object 上傳到另一台機器上的 WebAPI。
  5. 在源 MachineA 上有“FileA.txt”,在目標 MachineB 上有“FileB.txt”。

我認為這無關緊要,但我沒有計划用新名稱將文件寫回系統(MachineA),它將僅用於通過 Web ZDB974A738714CA8ACE14084 將文件 object(在內存中)發送到 MachineB。

我找到了一個使用反射來完成這個的解決方案......

FileStream fs = new FileStream(@"C:\myfile.txt", FileMode.Open);

var myField = fs.GetType()
    .GetField("_fileName", BindingFlags.Instance | BindingFlags.NonPublic)

myField.SetValue(fs, "my_new_filename.txt");

但是,自從給出該解決方案以來已經有幾年了。 2021年有沒有更好的方法來做到這一點?

另一種方法是在將文件名保存在 MachineB 上時定義文件名。 您可以將此文件名作為有效負載通過 Web API 並將其用作文件名。

//buffer as byte[] and fileName as string would come from the request
using (FileStream fs = new FileStream(fileName, FileMode.Create))
{
    fs.Write(buffer, 0, buffer.Length);
}

我能想到的最好方法是使用我多年前的舊方法。 下面展示了我是如何使用它的。 我這樣做只是為了掩蓋我要發送到的第三方 WebAPI 的原始文件名。

// filePath: c:\test\my_secret_filename.txt

private byte[] GetBytesWithNewFileName(string filePath)
{
    byte[] file = null;

    using (var fs = new FileStream(filePath, FileMode.Open, FileAccess.Read))
    {
        // Change the name of the file in memory (does not affect the original file)
        var fileNameField = fs.GetType().GetField(
            "_fileName",
            BindingFlags.Instance | BindingFlags.NonPublic
        );
        // If I leave out the next line, the file name field will have the full filePath
        // string as its value in the resulting byte array.  This will replace that with
        // only the file name I wish to pass along "my_masked_filename.txt".
        fileNameField.SetValue(fs, "my_masked_filename.txt");

        // Get the filesize of the file and make sure it's compatible with 
        // the binaryreader object to be used
        int fileSize;
        try { fileSize = Convert.ToInt32(fs.Length); }
        catch(OverflowException)
        { throw new Exception("The file is to big to convert using a binary reader."); }

        // Get the file into a byte array
        using (var br = new BinaryReader(fs)) { file = br.ReadBytes(fileSize); }
    }

    return file;
}

暫無
暫無

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

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