我有一个像 temp = "0101110011" 这样的二进制数字符串,我想将它保存为文件,这个临时文件有 10 个字符,我如何将此字符串保存到 10 位长度的文件?
void Save_Data(string temp)
{
bool[] BoolArray = new bool[temp.Length];
BitArray Barray = new BitArray(BoolArray.Length);
char[] ch = temp.ToCharArray();
for (int i = 0; i < temp.Length; i++)
{
if (ch[i] == '0')
{
Barray[i] = false;
}
else
{
Barray[i] = true;
}
}
Stream stream = new FileStream("D:\\test.dat", FileMode.Create);
StreamWriter sw = new StreamWriter(stream);
foreach (bool bit in Barray)
{
sw.Write(bit ? 1 : 0);
}
sw.Flush();
sw.Close();
}
Run Code Online (Sandbox Code Playgroud)
使用此代码,我的文件长度为 …