How to convert file to string to file in C#?

19,020

Solution 1

Convert your byte array to a base64 string, then back to a byte array on the other side.

Use

string content = Convert.ToBase64String(File.ReadAllBytes(filename));

and

File.WriteAllBytes(filename, Convert.FromBase64String(content));

Solution 2

I can't spot the error in your code, but I suggest that you better use StreamReader and StreamWriter.

var reader = new System.IO.StreamReader(filePath, System.Text.Encoding.UTF8);
var text = reader.ReadToEnd();

reader.Close();

var writer = new System.IO.StreamWriter(filePath, false, System.Text.Encoding.UTF8);

writer.Write(text);
writer.Close();

The false parameter passed to the StreamWriter constructor is to indicate that we don't want to append to the file if it exists.

Share:
19,020
MqDebug
Author by

MqDebug

Updated on June 14, 2022

Comments

  • MqDebug
    MqDebug almost 2 years

    I am writing an application that sends a file in text format from a machine to another i've used this code but apparently the reconstructed file is corrupted due to Encoding i think.

    //file to String
    byte[] bytes = System.IO.File.ReadAllBytes(filename);
    string text = System.Text.Encoding.UTF8.GetString(bytes);
    
    //String to file
    byte[] byteArray = Encoding.UTF8.GetBytes(text);
    FileStream ar = new FileStream("c:\\"+filename,System.IO.FileMode.Create);
    ar.Write(byteArray, 0, byteArray.Length);
    ar.Close();
    

    Is there any way to convert a file to string and back to file?

    Note: i want to convert all file types not only text files.

  • MqDebug
    MqDebug almost 11 years
    The code has no error. it works fine with converting text files but fails with files with different extentions(those that cannot be read using a text editor,exp Images,executables...) are corrupted when reconstructed.