I have the following code:
public static void PrependEntitiesToFile(string pathToFile)
{
char[] buffer = new char[10000];
FileInfo file = new FileInfo(pathToFile);
string renamedFile = file.FullName + ".orig";
System.IO.File.Move(file.FullName, renamedFile);
using (StreamReader sr = new StreamReader(renamedFile))
using (StreamWriter sw = new StreamWriter(file.FullName, false))
{
string entityDeclaration = "foo";
sw.Write(entityDeclaration);
string strFileContents = string.Empty;
int read;
while ((read = sr.Read(buffer, 0, buffer.Length)) > 0)
{
for (int i = 0; i < buffer.Length; i++)
{
strFileContents += buffer[i].ToString();
}
}
sw.Write(strFileContents, 0, strFileContents.Length);
}
System.IO.File.Delete(renamedFile);
}
This code works but its SOOOOO SLOW because I am looping through each character in the buffer
array and ToString()
-ing it. Imagine how slow it is when its ingesting and duplicating a 823,000 character file.
Is there a way to convert a fully populated buffer
to a string and add it at once rather than looping through each character in the array? Or, generically speaking, is there just a faster way to this?
I am so ashamed of this code.