tags:

views:

85

answers:

1

Just got some errors in code, which says the file is being used. What I need to achieve is add first part of encrypted data in file and then add second part of of evcrypted data in the same file. This file need to be decrypted later. I am pretty new to this field. Many thanks.

    Class3 cs3;
    StreamWriter sWriter;

    private void Add_text_Part_One()
    {
        Rijndael RijndaelAlg = Rijndael.Create();
        // Create a string to encrypt.
        string sData = "Here is some data to encrypt.";
        string FileName = @"C:\CText.txt";

        cs3 = new Class3(sData, FileName, RijndaelAlg.Key, RijndaelAlg.IV);
        sWriter = new StreamWriter(cs3.getCS());
        sWriter.WriteLine(sData);
        sWriter.Close();
    }

    private void Add_text_Part_Two()
    {
        string sData = "Here is some more data to encrypt.";
        sWriter.WriteLine(sData);
        sWriter.Close();
    }
class Class3
{
    FileStream fStream;
    Rijndael RijndaelAlg;
    CryptoStream cStream;
    public Class3(String Data, String FileName, byte[] Key, byte[] IV)
    {
        fStream = File.Open(FileName, FileMode.Append);
        RijndaelAlg = Rijndael.Create();
        cStream = new CryptoStream(fStream, RijndaelAlg.CreateEncryptor(Key, IV), CryptoStreamMode.Write); 
    }
    public CryptoStream getCS()
    {
        return cStream;
    }

    public string getRes()
    {
        StreamReader sReader = new StreamReader(cStream);
        string val = null;
        val = sReader.ReadLine();
        return val;
    }
+2  A: 

in the constructor of Class3 you call File.Open() and assign the resulting FileStream to fstream. This fstream object is never closed, so the file remains open. You are going to have to close the fstream (prefereably implement IDisposable and use Class3 within a using block)

Edit: Sorry, I think I'm kind of losing it here. I don't believe the above is right, however, you are closing the StreamWriter, and then trying to write to it again in part II, when it is closed, might want to take a look at that.

LorenVS
Does it work if I remove "sWriter.Close();" in first method?
Kelvin
All I can say is give it a shot...
LorenVS
does not workI will tidy up the code and try again.If it still doesnt work, will post it here.This one is closed. thx
Kelvin