0

I was wondering if you can help me out with this. I have a DataGridView with a couple of books saved on it. When I click on a book, the book's story loads in a RichTextBox. When I change that text and want to save it, I want to save the content in a .txt file. How can I go about it?

I have included code for you to see what I want to do.

string FileLine = "";
StreamWriter OutputFile;
foreach (Book book in myBookList)
{
    //Book Book = new Book();
    Book nBook = myBookList[dgv.CurrentCell.RowIndex];
    //PROBLEM IS HERE
    OutputFile = new StreamWriter(nBook.TxtFileName);
    //-------------------------------------------------------------
    //I want it to be something like this:  {nBook.TxtFileName}.txt
    //-------------------------------------------------------------
    //Code to write data to file
    OutputFile.WriteLine(FileLine);
    OutputFile.Close();
}

Thanks :)

JBTGE
  • 15
  • 3
  • See here: http://stackoverflow.com/questions/7306214/append-lines-to-a-file-using-a-streamwriter – Katie Kilian Oct 10 '14 at 15:07
  • 4
    Can not understand why not to use nBook.TxtFileName+".txt" – Sergey Malyutin Oct 10 '14 at 15:08
  • Hmm, I had interpreted this question as asking how to do the writing to the file, as opposed to how to get the filename to have ".txt" at the end. @JBTGE, which are you having problems with? – Katie Kilian Oct 10 '14 at 15:09
  • Thank you @Sergey Malyutin. That did the trick. I want to save the book's topic in the DataGridView as the file's name I am saving but could not get it to be of .txt type. Thank you! :) – JBTGE Oct 10 '14 at 15:16
  • Out of scope: please consider using `using`-statement or `try-finally` to make the code "exception safe" (dispose an instance of `StreamWriter`). – Sergey Vyacheslavovich Brunov Oct 10 '14 at 21:06

2 Answers2

2

Does this work? I hope so.

OutputFile = new StreamWriter(string.format("{0}.txt", nBook.TxtFilename));
Won Hyoung Lee
  • 383
  • 2
  • 14
  • Yes and I also found that the following is working: OutputFile = new StreamWriter(nBook.TxtFileName+".txt"); – JBTGE Oct 10 '14 at 15:20
-1

You have to declare it on your StreamWriter constructor, in your case:

OutputFile = new StreamWriter(nBook.TxtFileName + ".txt");
Katie Kilian
  • 6,815
  • 5
  • 41
  • 64
CapitanFindus
  • 1,498
  • 15
  • 26
  • @CaptainFindus It doesn't seem that the formatting is right with that, I suggest: `OutputFile = new StreamWriter(nBook.TxtFileName + ".txt");` – Wizard Oct 10 '14 at 15:13