I'm trying to read an EmbeddedResource (a default config file) and write it to a File. After that I should read the file and to make things easier I decided to do that in a single step.
private string CreateDefaultFile()
{
using (var stream = Shelter.Assembly.GetManifestResourceStream($@"Mod.Resources.Config.{_file}"))
{
if (stream == null)
throw new NullReferenceException(); //TODO
using (var ms = new MemoryStream())
{
using (var fs = new FileStream(Shelter.ModDirectory + _file, FileMode.Create, FileAccess.Write, FileShare.Read))
{
byte[] buffer = new byte[512];
int bytesRead;
while ((bytesRead = stream.Read(buffer, 0, buffer.Length)) > 0)
{
ms.Write(buffer, 0, bytesRead);
fs.Write(buffer, 0, bytesRead);
}
fs.Flush();
ms.Flush();
return Encoding.UTF8.GetString(ms.ToArray());
}
}
}
}
This does create the file but the return value doesn't seem to work as it should. The content seems correct but JSON.Net cannot parse it with this error:
JsonReaderException: Unexpected character encountered while parsing value: . Path '', line 0, position 0.
. Using File.ReadAllText(...)
instead of Encoding.UTF8.GetString(ms.ToArray())
seems to work so I'm guessing this is a problem with how I load the stream into a string.
Also the chunking part is not needed as the file is small in size, I've read in multiple places that is better use so I'd prefer it.
(Targeting .NET Framework 3.5
)