1

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";
            }
        }              
    }      
Zheng-rong Cai
  • 331
  • 2
  • 17
  • https://stackoverflow.com/questions/605685/how-to-both-read-and-write-a-file-in-c-sharp – mortb Jan 23 '19 at 13:30
  • 1
    Possible duplicate of [How to both read and write a file in C#](https://stackoverflow.com/questions/605685/how-to-both-read-and-write-a-file-in-c-sharp) – mortb Jan 23 '19 at 13:31
  • @mortb Well...for the most part it works i guess, but it doesn't write anything in the file if i use it like in that post. I want to be able to append, which uses `FileMode.Append`, but if i do that than i get an error that it only works in write-only.. – Zheng-rong Cai Jan 24 '19 at 10:21

2 Answers2

1

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.

thebear8
  • 139
  • 1
  • 9
  • So instead of getting all the text I split it in arrays with `private static string[] words = reader.ReadToEnd().Split(',');`. And together with `File.AppenAllText(path, "text");` (very clever way btw), it gave the error: "The process cannot access the file 'path' because it is being used by another process" – Zheng-rong Cai Jan 25 '19 at 14:04
  • I tried it in another solution **without** StreamReader and it worked, but now im still stuck with that error :'I...so close but yet so far... – Zheng-rong Cai Jan 25 '19 at 14:15
0

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.

thebear8
  • 139
  • 1
  • 9
  • I tried to use `using(){}` and i didn't get any errors. The only thing is that when i use my `StreamWriter` to add another word, it doesn't append anything (What it does do: not add the same word to the file). So my writer doesn't work and i have zero clue why, because i followed your instructions as well as those in the post that was a "duplicate". – Zheng-rong Cai Jan 24 '19 at 10:33
  • Did you get any exceptions when your StreamWriter didn't work? – thebear8 Jan 24 '19 at 14:12
  • What did you mean with "not add the same word to the file" ? – thebear8 Jan 24 '19 at 14:58
  • There are already some pre-written words in the file, so i don't have one word twice in the file. And the error i got when writer didnt work was something like 'can only append in write-only mode', but that error went away when i put the FileMode on .OpenOrCreate – Zheng-rong Cai Jan 25 '19 at 14:00
  • I think if you called `reader.Close();` just after `private static string[] words = reader.ReadToEnd().Split(',');` , it should work. You would have to reinitialize the StreamReader after that though. – thebear8 Jan 26 '19 at 12:42
  • Can't do that because it's not in a method. – Zheng-rong Cai Jan 26 '19 at 12:54
  • Oh nvm, it worked if i put reader.Close(); in all the methods i use reader in :D thanks! – Zheng-rong Cai Jan 26 '19 at 13:00
  • I posted another example in the previous answer, maybe it helps you. – thebear8 Jan 26 '19 at 13:01