Search code examples
c#bin

Creating the same bin file as content of string C#


I would like to create a bin file for example file.bin with the same content as a string variable contains. For example I have string str="10101" and I want to create conversion of str's content to bin file. After conversion, when I open file.bin I want to see the same content as str: 10101. I tried to do that by this way:

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();

but i get exception like

"System.IO.IOException: The process can not access the file "C:\path.."

because it is being used by another process.. and few more exception.


Solution

  • You get the error because you are opening the file twice. The second time fails because the file is already open.

    To write the string to the file you can just use the File.WriteAllText method:

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

    Note: The string is encoded as utf-8 when it is written to the file.