【问题标题】:Convert a File to Array in c# using System.IO使用 System.IO 在 c# 中将文件转换为数组
【发布时间】:2020-07-10 12:56:54
【问题描述】:

我在将文件转换为字节数组时遇到问题。所以我研究了最可靠的方法是通过这个:

byte[] bytes = System.IO.File.ReadAllBytes(filename);

问题是,我们的系统已经有类:System.csFile.cs。它与上述方法重叠。 FileSystem 这个词使用我现有的类作为参考。还有其他方法可以做到这一点吗? TIA

【问题讨论】:

  • 问问你的队友,他们一定是故意的。他们可能有自定义方法来替换 .net 标准方法。
  • global::System.IO.File.ReadAllBytes( filename );
  • @SirRufo 这解决了我的问题!谢谢!

标签: c# arrays file byte


【解决方案1】:

选项 1:using static directive

using static System.IO.File;
...
ReadAllBytes(filename);

选项 2:创建包装方法的单独类

using System.IO;
...
public static class FileReader
{
    public static byte[] ReadAllBytes(string filename) => File.ReadAllBytes(filename);
}

用法:

 FileReader.ReadAllBytes(filename);

选项 3:使用 global 命名空间

global::System.IO.File.ReadAllBytes(filename);

【讨论】:

    【解决方案2】:

    解决方案可以是为您自己的类或原始系统和文件类型使用命名导入。所以例如如果您想为标准库文件类型使用命名导入,您可以这样做以避免名称冲突:

    using SystemFiles = System.IO.File;
    

    这个链接也有一个例子: https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/using-directive

    【讨论】:

      【解决方案3】:

      你可以这样做:
      using MsSystem = System;

      然后在您的代码中:
      byte[] bytes = MsSystem.IO.File.ReadAllBytes(filename);

      或者;您可以使用 global 指代全局命名空间,它可用于解决您可能重新定义类型的问题。例如:

      class foo
      {
          class System
          {
      
          }
      
      }
      

      用法:

      global::System.IO.File.ReadAllBytes(filename);

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2016-12-13
        • 1970-01-01
        • 2010-10-15
        • 2018-02-05
        • 1970-01-01
        • 2015-08-25
        • 1970-01-01
        相关资源
        最近更新 更多