开发者

C# rijndael stream writer issue

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();
        re开发者_如何学运维turn val;
    }     


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜