【问题标题】:Creating the same bin file as content of string C#创建与字符串 C# 的内容相同的 bin 文件
【发布时间】:2015-04-30 11:20:58
【问题描述】:

我想创建一个 bin 文件,例如 file.bin,其内容与字符串变量所包含的内容相同。例如,我有字符串 str="10101",我想创建 str 的内容到 bin 文件的转换。转换后,当我打开 file.bin 时,我想看到与 str:10101 相同的内容。我尝试通过这种方式做到这一点:

string path = "files/file.bin";

string str = "10101"; 

File.Create(path);
BinaryWriter bwStream = new BinaryWriter(new FileStream(path, FileMode.Create));
BinaryWriter binWriter = new BinaryWriter(File.Open(path, FileMode.Create));
for (int i = 0; i < str.Length; i++)
{
    binWriter.Write(str[i]);
}
binWriter.Close();

但我得到了像

这样的异常

"System.IO.IOException: 进程无法访问文件 "C:\path.."

因为它正在被另一个进程使用.. 还有一些例外。

【问题讨论】:

  • 你想写 string 10101 还是你想写实际的二进制表示(即位)?
  • 该错误是因为您打开文件两次。只需删除 bwStream 行。
  • @Lloyd 我想写字符串 10101
  • 所以你基本上想要一个 UTF-16 编码的文本文件,其内容为"10101",文件扩展名为bin,而不是txt? -- 并且内容(例如)可以换成"hello world!" 或其他任何东西?

标签: c# bin


【解决方案1】:

您尝试访问的路径/文件已被其他应用程序使用。关闭所有可以/已经打开您正在创建的文件file.bin 的应用程序,然后关闭代码。它应该工作。如果没有其他应用程序正在运行,您可以删除 bwStream 变量行。

【讨论】:

  • 并确保文件位于您有权写入的位置...
  • 实际上它被同一个应用程序使用,因为 OP 打开一个流到文件,然后是一个写入器。
  • 是的,看到并修改了答案;)
【解决方案2】:

您收到错误是因为您打开文件两次。第二次失败,因为文件已经打开。

要将字符串写入文件,您只需使用File.WriteAllText method

string path = "files/file.bin";
string str = "10101"; 
File.WriteAllText(path, str);

注意:字符串写入文件时编码为utf-8。

【讨论】:

    【解决方案3】:

    File.Create()使用文件,试试:

    File.Create(path).Dispose();
    BinaryWriter bwStream = new BinaryWriter(File.Open(path, FileMode.Append, FileAccess.Write, FileShare.ReadWrite));
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-04-03
      • 2014-07-15
      • 2019-02-24
      • 2010-09-24
      • 1970-01-01
      • 2011-10-14
      • 1970-01-01
      相关资源
      最近更新 更多