public void Start()
        {
            List<Object> list = new List<Object>();
            List<Object> toRemove = new List<Object>();
            if (File.Exists("c.bin"))
            {
                using (Stream osR = File.OpenRead("c.bin"))
                {
                    DESCryptoServiceProvider cryptic = new DESCryptoServiceProvider();
                    cryptic.Key = ASCIIEncoding.ASCII.GetBytes("ABCDEFGH");
                    cryptic.IV = ASCIIEncoding.ASCII.GetBytes("ABCDEFGH");
                    try
                    {
                        using (CryptoStream crStream = new CryptoStream(osR, cryptic.CreateDecryptor(), CryptoStreamMode.Read))
                        {
                            if (osR.Length > 0)
                            {
                                byte[] data = ASCIIEncoding.ASCII.GetBytes(osR.ToString());
                                crStream.Read(data, 0, data.Length);
                                BinaryFormatter formatter = new BinaryFormatter();
                                Object obj = formatter.Deserialize(crStream);
                                 toRemove.Add(obj);
                            }
                        }
                    }
                    catch (CryptographicException e) { Console.WriteLine("error" + e.Message); }
            }
            Console.WriteLine("------------------");
            if (File.Exists("d.bin"))
            {
                using (Stream os = File.OpenRead("d.bin"))
                {
                    DESCryptoServiceProvider cryptic = new DESCryptoServiceProvider();
                    cryptic.Key = ASCIIEncoding.ASCII.GetBytes("ABCDEFGH");
                    cryptic.IV = ASCIIEncoding.ASCII.GetBytes("ABCDEFGH");
                    try
                    {
                        using (CryptoStream crStream = new CryptoStream(os, cryptic.CreateDecryptor(), CryptoStreamMode.Read))
                        {
                            if (os.Length > 0)
                            {
                                byte[] data = ASCIIEncoding.ASCII.GetBytes(os.ToString());
                                crStream.Read(data, 0, data.Length);
                                BinaryFormatter formatter = new BinaryFormatter();
                                Object obj = formatter.Deserialize(crStream);
                                if(!isContained(obj,toRemove)
                                   list.Add(obj);
                            }
                        }
                    }
                    catch (CryptographicException e) { Console.WriteLine("error" + e.Message); }
                }
            }
            if (!File.Exists("d.bin"))
                stream = File.Create("d.bin");
            foreach (Object obj in list)
            {
                if (obj is Product)
                    AddProduct((Product)obj);
                else
                {
                    if (obj is Department)
                        AddDepartment((Department)obj);
                    else
                    {
                        if (obj is Employee)
                            AddEmployee((Employee)obj);
                        else
                        {
                            if (obj is ClubMember)
                                AddClubMember((ClubMember)obj);
                            else
                            {
                                if (obj is Transaction)
                                    AddTransaction((Transaction)obj);
                                else
                                {
                                    if (obj is User)
                                        AddUser((User)obj);
                                }
                            }
                        }
                    }
                }
            }
            if(!File.Exists("c.bin")
               removeStream = File.Create("c.bin");
        }

        public void End()
        {
            stream.Close();
            removeStream.Close();
        }

        public void AddProduct(Backend.Product p)
        {
            productDB.Add(p);
            using (stream)
            {
                DESCryptoServiceProvider cryptic = new DESCryptoServiceProvider();
                cryptic.Key = ASCIIEncoding.ASCII.GetBytes("ABCDEFGH");
                cryptic.IV = ASCIIEncoding.ASCII.GetBytes("ABCDEFGH");
                    using (CryptoStream crStream = new CryptoStream(stream, cryptic.CreateEncryptor(), CryptoStreamMode.Write))
                    {
                        byte[] data = ASCIIEncoding.ASCII.GetBytes(stream.ToString());
                        crStream.Write(data, 0, data.Length);
                        BinaryFormatter seri = new BinaryFormatter();
                        seri.Serialize(crStream, p);
                    }
                }
            }

        }

i have the Start() function which initializes the program with previous data(which was inserted in previous uses in the program).
while running the program,the user can add things,such as products-then the AddProduct function is called and serializes it file.
my problem is that in the above code i get an error-"stream was not writable".
if i change the using line to-using(stream=File.OpenWrite("d.bin")) it's working but it overwrites the data already in the file and the next time i open the program i only see the last added object.
any suggestions on how to solve it or how change the code so this situation won't happen?

Recommended Answers

All 5 Replies

The File.OpenRead, is as you have pointed out locking the file access mode to read only, you should probaly just use Open, which is read\write.

When writing your stream, the position within the stream doesn't seem to have changed position, so any writing will occour from the first byte, overwriting exiting data.

However, looking at this it doesn't look like your file will have any pointer references each time you append data to your file. A new crypto stream will be written each time you write to the file, or indeed append the file however you will end up with a whole bunch of encrypted data chunks, with no reference in length for each one.

I would assume you would have to read all the data of the file, decode it, append the new data, encode it again then rewrite the files contents as a whole.

first of all,thanks :)
i thought about your suggestion too.
if i change the File.OpenRead to File.Open won't it fix the problem?

Assuming you are passing the same instance of stream to each of your Addxxx methods then yes it should work. However I think you need to do this using (CryptoStream crStream = new CryptoStream(stream, cryptic.CreateEncryptor(), CryptoStreamMode.Write)) only once at the start of the entire write process for all of your methods, not in each method.

using System;
using System.IO;
using System.Security.Cryptography;
using System.Text;

//The required variables

private static readonly byte[] initVectorBytes = Encoding.ASCII.GetBytes("tu89geji340t89u2");
private const int keysize = 256;


//Here the class for encryption:

public static string Encrypt(string plainText, string passPhrase)
{
  byte[] plainTextBytes = Encoding.UTF8.GetBytes(plainText);
  using (PasswordDeriveBytes password = new PasswordDeriveBytes(passPhrase, null))
  {
    byte[] keyBytes = password.GetBytes(keysize / 8);
    using (RijndaelManaged symmetricKey = new RijndaelManaged())
    {
      symmetricKey.Mode = CipherMode.CBC;
      using (ICryptoTransform encryptor = symmetricKey.CreateEncryptor(keyBytes, initVectorBytes))
      {
        using (MemoryStream memoryStream = new MemoryStream())
        {
          using (CryptoStream cryptoStream = new CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write))
          {
            cryptoStream.Write(plainTextBytes, 0, plainTextBytes.Length);
            cryptoStream.FlushFinalBlock();
            byte[] cipherTextBytes = memoryStream.ToArray();
            return Convert.ToBase64String(cipherTextBytes);
          }
        }
      }
    }
  }
}

//Here the code for decryption
public static string Decrypt(string cipherText, string passPhrase)
{
  byte[] cipherTextBytes = Convert.FromBase64String(cipherText);
  using (PasswordDeriveBytes password = new PasswordDeriveBytes(passPhrase, null))
  {
    byte[] keyBytes = password.GetBytes(keysize / 8);
    using (RijndaelManaged symmetricKey = new RijndaelManaged())
    {
      symmetricKey.Mode = CipherMode.CBC;
      using (ICryptoTransform decryptor = symmetricKey.CreateDecryptor(keyBytes, initVectorBytes))
      {
        using (MemoryStream memoryStream = new MemoryStream(cipherTextBytes))
        {
          using (CryptoStream cryptoStream = new CryptoStream(memoryStream, decryptor, CryptoStreamMode.Read))
          {
            byte[] plainTextBytes = new byte[cipherTextBytes.Length];
            int decryptedByteCount = cryptoStream.Read(plainTextBytes, 0, plainTextBytes.Length);
            return Encoding.UTF8.GetString(plainTextBytes, 0, decryptedByteCount);
          }
        }
      }
    }
  }
}

//And last, the output
//For Encryption
string encryptedstring = Encrypt("String you want to encrypt", "your encrypt password");
//For Decryption
string decryptedstring = Decrypt(encryptedstring, "your encrypt password");

Have you considered using a database? Are you trying to store all of the objects into a single file? How many records (entries) do you anticipate having for each object?

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.