从文件路径到使用资源

本文关键字:资源 文件 路径 | 更新日期: 2023-09-27 18:19:04

我当前的项目使用这个excel文档的直接文件路径来读取excel文件中的信息。我需要让我的项目准备发布,所以我不能有项目硬编码一个字符串形式的文件路径。

我想在我的资源中嵌入Excel文件,我已经做到了,但是我知道如何从资源中获得文件路径,并将文件路径发送给读取Excel文件的类。该类必须提供一个文件路径,所以我正在考虑复制这个Excel文件,然后在Temp文件夹中引用该类读取Excel文件的文件路径。

  FileName = @"D:'SomeFolder'ExcelFile.xlsx"; //This is the old code, hard coded
//I need code  that is going to make a copy of this file from the Resources and save it somewhere in a temp folder, but then give me
  the File path in the form of a string.
            string FileName; 
         // I need the file name to have the directory of this excel that is in the Resource folder

            //Call Class to Create XML File and store Data from BIN File Locally on Program
            ReadExcel_CreateXML = new ExcelRecorder(FileName);

从文件路径到使用资源

另外要考虑的是,您可能正在使用FileStreamBinaryReaderStreamReader读取当前文件。如果是这种情况,可以将文件的消费者写入为接受任意的Stream,然后您可以创建一个MemoryStream来传递给消费类:

// The resource will be a byte array, I'm just creating a
// byte array manually for example purposes.
var fileData = System.Text.Encoding.UTF8.GetBytes("Hello'nWorld!");
using (var memoryStream = new MemoryStream(fileData))
using (var streamReader = new StreamReader(memoryStream))
{
    // Do whatever you need with the file's contents
    Console.WriteLine(streamReader.ReadLine());
    Console.WriteLine(streamReader.ReadLine());
}

这种方法意味着您不会用需要清理的临时文件把客户机计算机弄得乱七八糟。这也意味着如果您需要处理任何其他类型的Stream的数据,您的消费类将变得更加灵活。

我不确定这是否是最好的解决方案,但它会起作用:

首先在资源中获取文件的byte[]数组:

byte[] fileByteArray = global::YourProjectNameSpace.Properties.Resources.ExcelFileName

2使用以下函数将文件导出到临时位置:(我从这里得到:写入字节到文件)

public bool ByteArrayToFile(string _FileName, byte[] _ByteArray)
        {
            try
            {
                // Open file for reading
                System.IO.FileStream _FileStream =
                   new System.IO.FileStream(_FileName, System.IO.FileMode.Create,
                                            System.IO.FileAccess.Write);
                // Writes a block of bytes to this stream using data from
                // a byte array.
                _FileStream.Write(_ByteArray, 0, _ByteArray.Length);
                // close file stream
                _FileStream.Close();
                return true;
            }
            catch (Exception _Exception)
            {
                // Error
                Console.WriteLine("Exception caught in process: {0}",
                                  _Exception.ToString());
            }
            // error occured, return false
            return false;
        }

最后访问临时文件

使用:

在表单中创建一个按钮,并将此代码放入按钮的click事件

private void button1_Click(object sender, EventArgs e)
    {
        byte[] fileByteArray = global::YourProjectNameSpace.Properties.Resources.ExcelFileName;
        if (ByteArrayToFile(@"C:'Temp'file.xlsx", fileByteArray))
        {
            //File was saved properly
        }
        else
        {
            //There was an error saving the file
        }
    }

希望能成功