Hi all,

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.
J

Dani AI

Generated

Good that found the quick concatenation fix and reminded you to confirm the value is a valid path. A couple of practical follow-ups to make the save robust and avoid subtle bugs:

Your original snippet loops over the whole book list but then always uses the current DataGridView selection; that will repeatedly act on the same book. Only take the selected book once, then build a safe file path and write it. Sanitize the filename portion, ensure the directory exists, handle common IO exceptions, and prefer helper APIs (Path, File) over manual string concatenation.

Example pattern (replace names to match your form controls):

var book = myBookList[dgv.CurrentCell.RowIndex];
string folder = Path.GetDirectoryName(book.TxtFileName) ?? Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
string name = Path.GetFileNameWithoutExtension(book.TxtFileName);
foreach (char c in Path.GetInvalidFileNameChars()) name = name.Replace(c, '_');
string filePath = Path.Combine(folder, name + ".txt");

try
{
    Directory.CreateDirectory(folder);
    File.WriteAllText(filePath, richTextBox.Text, Encoding.UTF8);
}
catch (IOException) { /* disk full / locked file */ }
catch (UnauthorizedAccessException) { /* permission issue */ }

Other tips: use SaveFileDialog when you want the user to choose location; consider File.WriteAllTextAsync to avoid blocking the UI; use Path.ChangeExtension if you want to replace any existing extension; and always validate the final path before writing. These steps prevent invalid filenames, accidental overwrites, and most runtime errors you might otherwise see.

Recommended Answers

All 2 Replies

What is the value of Book.TxtFileNameat present?

Just need to make sure it is a filepath ie C:\Desktop\nBook.txt and it should be fine to save as a .txt file

I managed to get it working. The solution is quite simple.

line 10 should be: OutputFile = new StreamWriter(nBook.TxtFileName+".txt");

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.