Editting a file programatically

Hey guys,
I am working on an application that needs to open a file that has only one line, encrypt the content, and save it.  I don't want to create a new file; just want to open the file, make my changes and save it.  I am using the objects "streamreader" and "streamwriter" to accomplish this.  The problem I'm having is that when I decrypt the file might be somewhat corrupted.  My encryption code is very stable and works great(we use it for all our applications).  I am thinking it could be the way I'm writing to the file that is creating the problem.  Here is the code snippet:

string sLine = string.empty;
string sEncrypt = string.empty;

// Read the line from the file and encrypt it
using(StreamReader myReader = new StreamReader(@"c:\test.txt"))
{
      while((sLine = myReader.ReadLine()) != null)
      {
          // encrypt the message
          sEncrypt = myComponent.Encrypt(sLine);
      }
}

// Write the encrypted line back to the file                  
using(StreamWriter myWriter = new StreamWriter(@"c:\test.txt"))
{
      myWriter.WriteLine(sEncrypt );
      myWriter.Flush();
      myWriter.Close();
}

Is there another way I can try to manipulate the files.  Any suggestions appreciated.


fifo123Asked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Fernando SotoRetiredCommented:
Are you closing the StreamReader before writing to it with StreamWriter?
Bob LearnedCommented:
Use Unicode encoding with the stream reader/writer, otherwise the default encoding will mess up the encrypted text:

      using(StreamReader myReader = new StreamReader(@"c:\test.txt", new System.Text.UnicodeEncoding() ))

      using(StreamWriter myWriter = new StreamWriter(@"c:\test.txt", new System.Text.UnicodeEncoding() ))

Bob

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
C#

From novice to tech pro — start learning today.