How can you write over the contents of a text file when using a StreamWriter that takes a MemoryStream as a parameter?

I want to load a text file that is in my Resources folder, then use a StreamWriter to write to the text file.

I load the text file with :

TextAsset textFile = Resources.Load(path);

Then do the StreamWriter by converting the TextAsset to a MemoryStream :

using(StreamWriter writer = new StreamWriter(new MemoryStream(textFile.bytes)))
{

}

The code executes, but the contents of the text file are not wrote over like I want it to be. If I use a StreamWriter and just pass in the path to the text file, with a second parameter of false, this works as I intend it to and writes over the contents of the text file. I however want to load the text file from the Resources folder because using StreamWriter with a path doesn’t work when I build on Android.

Is there a way to use a StreamWriter like this where you pass in a MemoryStream but can still write over the contents of the file?

Assets can’t be changed at runtime. TextAssets are like any other assets in a build project. They are readonly. There is no way to permanentally alter an asset at runtime as all assets are packed into the asset database.

If you want to be able to store data in a built game you have to use an actual file path.

The StreamWriter does wotk with a path on Android as long as you pass a valid path. Android is very strict with permissions. You can only write to certain locations. If you want to save anything on android you should use the persistent data path. There you can store files and even create subfolders.

You can not store anything at Application.dataPath as this just points to the APK file. The actual apk file is located in a protected folder of the OS.

If you want to ship a text file with your app which you want to edit during runtime you usually try to load the file from the persistent data path first and if it fails load it from the TextAsset. When you want to save the file you create or overwrite the file in the persistent data path.

Besides that your code can never overwrite the file where the “bytes” come from. When you read the bytes array you just get back an array with all the content of the file. At this point the array has no connection to the file or asset. A MemoryStream just works on the array you give it as buffer.