2

I have a problem trying to create a file via FileStream, for some reason when the variable time receives the data in a way everything works fine, but if I close the program and open it again and that variable comes from a csv file I get this error : "System.ArgumentException: 'Illegal characters in path.' I did a MessageBox.Show on the pathSave variable and the result is correct "C:\Users\Felipe\AppData\Local\Temp\diskSTLQUZFTOV.vhd" I don't know why it's not showing this way via csv.

private void FileEncrypt(string outFile, string password, string time)
        {
            byte[] salt = GenerateRandomSalt();
            FileStream fsCrypt = new FileStream(outFile, FileMode.Create);
            byte[] passwordBytes = Encoding.UTF8.GetBytes(password);
            RijndaelManaged AES = new RijndaelManaged();
            AES.KeySize = 256;
            AES.BlockSize = 128;
            AES.Padding = PaddingMode.PKCS7;
            Rfc2898DeriveBytes key = new Rfc2898DeriveBytes(passwordBytes, salt, 50000);
            AES.Key = key.GetBytes(AES.KeySize / 8);
            AES.IV = key.GetBytes(AES.BlockSize / 8);
            AES.Mode = CipherMode.CFB;
            fsCrypt.Write(salt, 0, salt.Length);
            CryptoStream cs = new CryptoStream(fsCrypt, AES.CreateEncryptor(), CryptoStreamMode.Write);
            string pathSave = Path.GetTempPath() + "disk" + time + ".vhd";
            MessageBox.Show(pathSave);
            FileStream fsIn = new FileStream(pathSave, FileMode.Open);
            byte[] buffer = new byte[1048576];
            int read;
            try
            {
                while ((read = fsIn.Read(buffer, 0, buffer.Length)) > 0)
                {
                    Application.DoEvents();
                    cs.Write(buffer, 0, read);
                }
                fsIn.Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error: " + ex.Message, "Unmount Encryption - Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            finally
            {
                cs.Close();
                fsCrypt.Close();
            }
        }
Tomás
  • 23
  • 4

1 Answers1

1

You can simply replace any invalid characters from the path before saving like this:

char[] invalidChars = Path.GetInvalidFileNameChars();
string correctedFormatTime = time;
foreach (char c in invalidChars)
{
    correctedFormatTime = correctedFormatTime.Replace(c.ToString(),"");
}
string pathSave = Path.GetTempPath() + "disk" + sanitizedTime + ".vhd";
MD Zand
  • 2,366
  • 3
  • 14
  • 25