Click here to Skip to main content
15,900,676 members
Please Sign up or sign in to vote.
2.00/5 (1 vote)
See more:
Hello,
how do i use StreamWriter in a windows form without my function resetting the xxx.txt file ?I'm workng on a small Model View Controller project.
ex: in my controller class:

  FileInfo f=new FileInfo("LibraryFiles.txt");
  StreamWriter Swriter;

  public void AddFile(Object ob)
  {
   Swriter=f.CreateText();
   Swrite.Writeline(ob);
   Swrite.Write(Swrite.NewLine);
   Swriter.Close();
   //if i close my file here then i can't put anymore Object
   //get error can't put in closed file
  }

 //i only can get the last element enterred because the file is
 //recreated all the time i call this method.
 //In My GUI it's fine other methods work perfectly.

buttonclick ...()
{
   myInstance.AddFile(object)
}
Posted
Updated 23-Jan-10 9:03am
v2

What error do you get? Does it throw an exception or fail silently? It might be helpful if you edit your question to include this info.

You need to call Dispose() on SWriter after you Close() it, or better yet use it in a using statement to have the framework do it for you.

If you want to append data instead of overwriting it then you'll need to use Open with the proper parameters instead of CreateText().
 
Share this answer
 
v2
This all seems flawed to me. Why would you pass an object to this method ? Why would you close the file, and never open it again ? Why wouldn't you use a try/catch/finally block to make sure the file is always properly closed and reopened ? As you're creating a text file, why not just take a string as a parameter ( that's what you end up writing in any case ), and use File.AppendAllText, if you want to append to your file. or File.WriteAllText if you want to erase the old file and create a new one ?
 
Share this answer
 
Hello,
-The error I get is an exception "cannot write in a closed file"
-The function has an object argument because WriteLine() has an overload that receives an object argument, string, int...as long as the object overrides ToString() it works okay.

But that's not my problem I'd like to know how to position the codes in my program. The same code works in Console application !

It's my first time to use this forum I don't know if sending codes is okay. In case it's not - Sorry :)
Here is the code in console:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
namespace StreamReadWrite
{
    class Program
    {
        static void Main(string[] args)
        {
            Person p = new Person();
            p.Name = "jeannette";
            p.Id = 666;
            Person p1 = new Person();
            p1.Name = "Jonathan";
            p1.Id = 43443;
            //Create and Write into a file
            FileInfo f = new FileInfo("ReadWriteTest.txt");
            StreamWriter Swriter = f.CreateText();
            Swriter.WriteLine(" mama is my witness");
            Swriter.WriteLine(p);
            Swriter.WriteLine(p1);
            Swriter.WriteLine(" I love programming in c#");
            Swriter.Write(Swriter.NewLine);
            Swriter.Close();
            Console.WriteLine("The file ReadWriteTest has been created ");
            //
            //Read from the file
            StreamReader Sreader = File.OpenText("ReadWriteTest.txt");
            string input = "";
            while ((input = Sreader.ReadLine()) != null)
            {
                Console.WriteLine(input.ToString());
            }
            Sreader.Close();
            //return 0;
            Console.Read();
        }
        public class Person
        {
            public string Name { get; set; }
            public int Id { get; set; }
            public override string ToString()
            {
                return " Name : "+Name+" "+"Id :"+Id;
            }
        }
    }
}
 
Share this answer
 
v3
Please edit your post, don't post an 'answer' that's really not an answer at all.

-The error I get is an exception "cannot write in a closed file

I've already explained why this is. You close the file but you don't reopen it. Either keep the file open for the life of the program, or write code to properly handle opening and closing it every time. OR let the framework do it for you, with the methods I pointed out.

-The function has an object argument because WriteLine() has an overload that receives an object argument, string, int...as long as the object overrides ToString() it works okay.

Sure it does. But, if you take a string, then you have more explicit control, you need a string at the end of the day, so why not just have a method that takes a string, and, if you must, an override that takes an object and calls the string param version with a ToString call ?

But that's not my problem I'd like to know how to position the codes in my program. The same code works in Console application !"

Your console app does not contain a method that is called over and over. If you copied the same code over, you'd have the same problem. I have to say, the error message says your stream is closed, you call sWriter.Close() in your code, I don't see how this issue is remotely complex to understand. You close your stream, and you don't open it. it's therefore closed, and cannot be written to as a result.

As for laying out your code, if you use the streamwriter only in this method, it's dumb to make it a member variable. It adds to the issue, it being a member is why it's held in a closed state, and in that state when you try to use it without opening it again.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900