Why is StreamWriter not working?

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • shockna1
    New Member
    • Apr 2010
    • 30

    Why is StreamWriter not working?

    Im trying to write a class to replace strings in a text file but for some reason StreamWriter will not work in my class. Its not throwing any exceptions or anything its just not writing to the text file. Also I used to have a destructor in my class but it was throwing an exception when I tried to close or dispose outFile.

    Code:
    class TextReplacer
    {
        private StreamReader inFile;
        private StreamWriter outFile;
    
        public TextReplacer(StreamReader _in, StreamWriter _out)
        {
            inFile = _in;
            outFile = _out;
    
            outFile.WriteLine("TESTING!!!"); // DOES NOT WORK
        }
    
        public void Repace(string find, string replace)
        {
            string line = inFile.ReadLine();
    
            if (line != null)
            {
                line = line.Replace(find, replace);
    
                Console.WriteLine(line);
    
                outFile.WriteLine(line); // DOES NOT WORK
    
                Repace(find, replace);
            }
    
            return;
        }
    }
    Last edited by Niheel; Apr 17 '11, 07:40 AM.
  • Aimee Bailey
    Recognized Expert New Member
    • Apr 2010
    • 197

    #2
    I'm betting this is probably because you still have the file open in read-only mode. A quick way to do what your trying to do could be:

    Code:
    public void ReplaceInFile(string file, string find, string replace)
    {
    	string buffer = File.ReadAllText(file);
    	buffer = buffer.Replace(find, replace);
    	File.WriteAllText(file, buffer);
    }
    However if you needed to use StreamReader and StreamWriter within a class, then this is probably what your looking for:

    Code:
    public void Replace(string find, string replace)
    {
    	string buffer = "";
    	using(FileStream fs = new FileStream(m_Filename, FileMode.OpenOrCreate, FileAccess.ReadWrite))
    	{
    		StreamReader sr = new StreamReader(fs);
    		buffer = sr.ReadToEnd();
    				
    		buffer = buffer.Replace(find, replace);
    			
    		fs.Position = 0;
    				
    		using(StreamWriter sw = new StreamWriter(fs))
    		{
    			sw.Write(buffer);
    			sw.Flush();
    			sw.Close();
    			sr = null;
    		}
    	}	
    }
    All the best.

    Aimee.
    Last edited by Aimee Bailey; Apr 20 '11, 02:36 PM. Reason: Should have debugged this first.

    Comment

    Working...