zhrgci
zhrgci

Reputation: 686

C# Can I use FileStream for StreamReader(fs) and StreamWriter(fs, append: true) at the same time?

So basically i was struggling with hangman and i couldn't figure out how to solve it the first problem. That's why i thought i might put in another function; a method to add a word to my textfile of words with StreamWriter using FileStream. (I have a StreamReader too, so i can see what random word it would choose.)

Things tried (with all: writer.WriteLine(text)):

  1. I tried using StreamWriter writer = new StreamReader(fs.ToString(), append: true) with FileStream fs = new FileStream(path, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None)

  2. I tried FileMode.Append (because i want to append), but that only works in write-only mode and i need to read text too.

  3. I tried to use the filestream without the ToSting(), but that resulted in "Cannot convert from 'System.IO.FileStream' to 'string'."

  4. I tried to do the same thing in a different program but only with StreamReader and FileStream, but it still didn't change anything in the textfile.

What I actually wish it would do: I expect that the program will be able to append a string to the textfile while still being able to read the chosen word. (When you start the program a random word out of the textfile is chosen.)

Sorry if this looks messy, it's my first time asking a question on stackoverflow.

So why this is different from the duplicate is because i want to append the file, not write (overwrite) it. I tried the exact same FileStream as the "duplicate", but it only got rid of the error. Now I'm still stuck with a malfunctioning StreamWriter.

Part of the code:

    private static FileStream fs = new FileStream(path, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None);
    private static StreamReader reader = new StreamReader(fs);

    private static string[] words = reader.ReadToEnd().Split(',');

    public static Random randomizer = new Random();
    private static int wordindex = randomizer.Next(0, words.Length);


    public string GetWord()
    {
        return words[wordindex]; //returns random value out of array = random woord
    }

`

And using for StreamWriter:

public string AddWordToFile(string word)
    {
        using (StreamWriter writer = new StreamWriter(fs.ToString(), append: true))
        {
           //bool ExistsInFile = false;
            for (int i = 0; i < words.Length; i++)
            {
                if (words.Contains(word))
                {
                    //ExistsInFile = true;
                    return "The word '" + word + "' already exists in the textfile.";
                }
            }
            if (!words.Contains(word))
            {
                //ExistsInFile = false;
                writer.WriteLine("," + word);
                writer.Close();
                return word + " added.";
            }
            else
            {
                return "Whoops, something went wrong :'I";
            }
        }              
    }      

Upvotes: 1

Views: 1042

Answers (2)

thebear8
thebear8

Reputation: 312

Another way to do it would be this:

    static void ReadAndWrite()
    {
        string file = File.ReadAllText(@"C:\whatever.txt"); //read C:\whatever.txt
        File.AppendAllText(@"C:\whatever.txt", "Text to append"); //append "Text to append" to C:\whatever.txt
    }

I've tested this and it works just fine on my PC.

Maybe it helps you.

Edit: This is much easier and reads every line in a file into a string array:

    static void ReadAndWrite()
    {
        string[] words = File.ReadAllLines(@"C:\whatever.txt");
        File.AppendAllText(@"C:\whatever.txt", "Word to append\r\n"); //append "Word to append" in a new Line to C:\whatever.txt
    }

To get an array of words, write every word into a new line by also appending \r\n after every word like in the example. This way, you get an array of every word in your file.

Upvotes: 1

thebear8
thebear8

Reputation: 312

I think the problem is that you had two different FileStreams accessing the same file at once which doesn't work. One way to do this would be to close the FileStreams and StreamWriters right after using them and everytime you Need to Access the file reopen it.

To close the StreamWriter/FileStream, use:

StreamWriter.Close();

or for FileStreams:

FileStream.Close();

You will obviously have to replace FileStream trough the Name of your FileStream object.

I hope I could help you.

Upvotes: 0

Related Questions