Read text files

Hi,
I’m trying to read text files by

var filePath = Path.Combine(Content.RootDirectory, "score.txt"); using (var stream = TitleContainer.OpenStream(filePath)) { text = File.ReadAllText(filePath); }

In the content pipeline i set build action to ‘Copy’. When run the code it says Could not find a part of the path “/Content/score.txt”.

thanks
lasa

If you’ve already opened a stream of the file with

using (var stream = TitleContainer.OpenStream(filePath))
{
  ...
}

you probably don’t wanna be using File.ReadAllText() while that stream is opened. Even if the file exists, the operating system won’t like you trying to read the file twice at the same time like you would be with that code - and you’ll get a “The process cannot access the file because it is being used in another process” error.

Instead, give this a try.

var filePath = Path.Combine(Content.RootDirectory, "score.txt");
using (var stream = TitleContainer.OpenStream(filePath))
{
  using (var reader = new StreamReader(stream))
  {
    string text = reader.ReadToEnd();
  }
}

Assuming you’re getting the “File not found” error when you call File.ReadAllText and NOT when you open the stream, the above code should work perfectly for you.

1 Like

Thanks, it’s working.