public void SaveAs()
{
if(dataGridView1.ColumnCount>=2)
{
SaveFileDialog saveFileDialog = new SaveFileDialog();
saveFileDialog.Filter = "Excel files (*.xls)|*.xls";
saveFileDialog.FilterIndex = 0;
saveFileDialog.RestoreDirectory = true;
saveFileDialog.CreatePrompt = true;
saveFileDialog.Title = "Export Excel File To";
saveFileDialog.ShowDialog();
Stream myStream;
myStream = saveFileDialog.OpenFile();
StreamWriter sw = new StreamWriter(myStream, System.Text.Encoding.GetEncoding(-0));
string str = "";
try
{
for (int i = 0; i < dataGridView1.ColumnCount; i++)
{
if (i > 0)
{
str += "\t";
}
str += dataGridView1.Columns[i].HeaderText;
}
sw.WriteLine(str);
for (int j = 0; j < dataGridView1.Rows.Count; j++)
{
string tempStr = "";
for (int k = 0; k < dataGridView1.Columns.Count; k++)
{
if (k > 0)
{
tempStr += "\t";
}
tempStr += dataGridView1.Rows[j].Cells[k].Value.ToString();
}
sw.WriteLine(tempStr);
}
sw.Close();
myStream.Close();
}
catch (Exception e)
{
// MessageBox.Show(e.ToString());
}
finally
{
sw.Close();
myStream.Close();
}
}
else
MessageBox.Show("No data to save", "OK",
MessageBoxButtons.OKCancel, MessageBoxIcon.Asterisk);
}
When I open the saving window and I decide not to save DataGridView1 by clicking Cancel I have an error Index was outside the bounds of the array. at
myStream = saveFileDialog.OpenFile();
I don't know what's wrong in here.
Your culprit code is here:
saveFileDialog.ShowDialog();
Stream myStream;
myStream = saveFileDialog.OpenFile();
It should be like such:
if (saveFileDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK) {
// code here for user pressing OK instead of the 'X' or 'Cancel'
Stream myStream = saveFileDialog.OpenFile();
}
Without that check if you close the dialog (via the 'x') or press Cancel, your saveFileDialog has some "empty" values that you try and reference (which gives you the error).
The function ShowDialog() returns a DialogResult to determine what action was taken. Just check the return value there before you continue. For example:
if(saveFileDialog.ShowDialog() == DialogResult.Cancel)
{
//do something else here or just return
return;
}
I have an app that reads a directory, gets a list of the files (segy) and populates a listbox on the left side of the app with the filenames. Upon clicking an item in the listox I'd like the rich text box on the right to display the content of the file.
I have the app working if I use the openfiledialog to select one of the files in the directory, I'm having issues trying to get the stream reader to read the selected file I've clicked.
The working simple openfiledialog code below.
openFileDialog1.Filter = "All Files|*.*";
openFileDialog1.Title = "Open SEG-Y Files";
DialogResult result = openFileDialog1.ShowDialog();
StreamReader readFile = new StreamReader(openFileDialog1.FileName, ebcdic);
readFile.BaseStream.Seek(0, SeekOrigin.Begin);
readFile.Read(data, 0, 3200);
string stringData = "";
for (int i = 0; i < data.Length; i++)
{
if ((i % 80) == 0 && stringData != "")
stringData += Environment.NewLine;
stringData += data[i].ToString();
}
rtbHeader.Text = stringData;
rtb.AppendText(value);
rtb.AppendText(System.Environment.NewLine);
My code
private void txtUpdate(string value)
{
lstFiles.Items.Add(value + Environment.NewLine);
lstFiles.TopIndex = lstFiles.Items.Count - 1;
lstFiles.Update();
}
private void btnFolder_Click(object sender, EventArgs e)
{
txtPath.Text = "";
lstFiles.Items.Clear();
rtbHeader.Clear();
DialogResult result = folderBrowserDialog1.ShowDialog();
if (result == DialogResult.OK)
{
txtPath.Text = folderBrowserDialog1.SelectedPath;
}
}
private void btnFiles_Click(object sender, EventArgs e)
{
lstFiles.Items.Clear();
string path = txtPath.Text;
List<string> files = new List<string>(Directory.EnumerateFiles(txtPath.Text, "*.sgy", SearchOption.AllDirectories).Select(Path.GetFileName).OrderBy(x => x));
if (files == null || files.All(x => string.IsNullOrWhiteSpace(x)))
{
MessageBox.Show("There are no files with extension" + " sgy", "Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
return;
}
foreach (string file in files)
{
this.Invoke(new Action(() => txtUpdate(file)));
}
}
private void lstFiles_MouseClick(object sender, MouseEventArgs e)
{
rtbHeader.Clear();
String item = (Convert.ToString(lstFiles.SelectedItem));
//MessageBox.Show(item);
StreamReader readFile = new StreamReader(item, ebcdic);
readFile.BaseStream.Seek(0, SeekOrigin.Begin);
readFile.Read(data, 0, 3200);
string stringData = "";
for (int i = 0; i < data.Length; i++)
{
if ((i % 80) == 0 && stringData != "")
stringData += Environment.NewLine;
stringData += data[i].ToString();
}
rtbHeader.Text = stringData;
}
}
Im getting an Illegal characters in path exception on this bit.
StreamReader readFile = new StreamReader(item, ebcdic);
Thanks
The code example really should be simpler. Much simpler. And the problem description more specific. Much more specific. See https://stackoverflow.com/help/mcve and https://stackoverflow.com/help/how-to-ask
That said, I believe that if you change this statement in the txtUpdate() method:
lstFiles.Items.Add(value + Environment.NewLine);
to this:
lstFiles.Items.Add(value);
It will work. The exception is most likely caused by the fact that you have newline characters in your strings. Not only does that make the filename not the one you want, it's not a valid character in Windows paths.
Also note that the items in the ListBox you've added are already strings. You don't need to call Convert.ToString() on them. You can just cast them back to a string:
String item = (string)lstFiles.SelectedItem;
This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 10 years ago.
i am having two problems:
1- when ever i click on open button, it shows me the openfiledialog twice (when i select my file and click ok, it reopens the selection windows again, only repeats it once).
2- i am trying to export and import text files from a list view, so far i managed to export a text file from the list view, but i failed at importing it back in.
here is my code (for both situations since it's the same project):
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
string path;
//string fname;
private void abtmenuItem10_Click(object sender, EventArgs e)
{
MessageBox.Show("DB Kai UB Text Extractor\n by Omarrrio 2012", "About...", MessageBoxButtons.OK, MessageBoxIcon.Information, MessageBoxDefaultButton.Button1, 0, "http://gbatemp.net/user/245642-omarrrio/");
}
private void exitmenuItem4_Click(object sender, EventArgs e)
{
this.Close();
}
private void sbtmenuItem5_Click(object sender, EventArgs e)
{
listView1.Items.Clear();
OpenFileDialog ofd = new OpenFileDialog();
ofd.Title = "Open Sbt File";
ofd.Filter = "Sbt Files (*.sbt)|*.sbt|All Files (*.*)|*.*";
//if (ofd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
}
private void msgmenuItem6_Click(object sender, EventArgs e)
{
listView1.Items.Clear();
pntrsmenuItem4.Text = "Number of Pointer = ";
OpenFileDialog ofd = new OpenFileDialog();
ofd.Title = "Open Msg File";
ofd.InitialDirectory = Application.StartupPath;
ofd.Filter = "Msg Files (*.msg)|*.msg|All Files (*.*)|*.*";
DialogResult result = ofd.ShowDialog();
if (result == DialogResult.Cancel)
return;
if (ofd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
path = ofd.FileName;
BinaryReader br = new BinaryReader(File.OpenRead(path), Encoding.GetEncoding("Shift_JIS"));
br.BaseStream.Position = 0x4;
int num_pointers = br.ReadInt16();
if (num_pointers == 0x56C)
{
MessageBox.Show("This File is not supported as it's pointer system is somehow F*cked up, please use another file, thank you.","Error",MessageBoxButtons.OK,MessageBoxIcon.Error);
return;
}
else
{
MessageBox.Show("File opened Succesfully!", "Info", MessageBoxButtons.OK, MessageBoxIcon.Information);
pntrsmenuItem4.Visible = true;
pntrsmenuItem4.Text += num_pointers.ToString();
List<int> offsets = new List<int>();
for (int i = 2; i <= (num_pointers * 2); i += 2)
{
br.BaseStream.Position = i * 4 + 4;
offsets.Add(br.ReadInt32());
//listView1.Items.Add(br.ReadUInt32().ToString("X"));
}
Dictionary<int, string> values = new Dictionary<int, string>();
for (int i = 0; i < offsets.Count; i++)
{
int currentOffset = offsets[i];
int nextOffset = (i + 1) < offsets.Count ? offsets[i + 1] : (int)br.BaseStream.Length;
int stringLength = (nextOffset - currentOffset - 1) / 2;
br.BaseStream.Position = currentOffset;
var chars = br.ReadChars(stringLength);
values.Add(currentOffset, new String(chars));
}
foreach (int offset in offsets)
{
listView1.Items.Add(offset.ToString("X")).SubItems.Add(values[offset]);
}
br.Close();
br = null;
}
}
ofd.Dispose();
ofd = null;
}
private void EtxtmenuItem8_Click(object sender, EventArgs e)
{
SaveFileDialog sfd = new SaveFileDialog();
sfd.Title = "Save Text File";
sfd.DefaultExt = ".txt";
sfd.InitialDirectory = Application.StartupPath;
sfd.Filter = "Text Files (*.txt)|*.txt";
DialogResult result = sfd.ShowDialog();
if (result == DialogResult.Cancel)
return;
StreamWriter wwrite = new StreamWriter(sfd.FileName, false, Encoding.Unicode);
for (int i = 0; i < listView1.Items.Count; ++i)
{
string name = listView1.Items[i].SubItems[1].Text;
wwrite.WriteLine("-" + name);
}
wwrite.Close();
}
private void ItxtmenuItem4_Click(object sender, EventArgs e)
{
OpenFileDialog ifd = new OpenFileDialog();
ifd.Title = "Open Text File";
ifd.Filter = "Text Files (*.txt)|*.txt";
ifd.InitialDirectory = Application.StartupPath;
DialogResult result = ifd.ShowDialog();
if (result == DialogResult.Cancel)
return;
StreamReader sr = new StreamReader(ifd.FileName);
int aa = 0;
while (sr.Peek() >= 0)
{
string[] a2 = sr.ReadLine().Split('-');
if (a2.Length == 2)
{
aa = int.Parse(a2[0].ToString());
listView1.Items[aa].SubItems[1].Text = a2[1].Replace("~", "\n");
}
else
{
listView1.Items[aa].SubItems[1].Text += "\n" + a2[0];
}
}
sr.Close();
}
}
It's a bit hard to see which Menu click corresponds to which method here, but I'll I'm guessing that the offending piece of code is msgmenuItem6_Click.
The reason that the Dialog is showing up twice is because you call ShowDialog twice.
DialogResult result = ofd.ShowDialog();
if (result == DialogResult.Cancel)
return;
if (ofd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
You should be doing
if (result == System.Windows.Forms.DialogResult.OK)
Regarding why you aren't able to read your file. Are you certain that there is data in the while you're trying to read? To ensure that you are opening it correctly, you can also try File.ReadAllText and make sure that it's being read in correctly.
i have application with Listbox and files, each time i press on Add button the default C drive open and i want the application to remember the last path i used
private void btnAdd_Click(object sender, EventArgs e)
{
System.IO.Stream myStream;
OpenFileDialog thisDialog = new OpenFileDialog();
thisDialog.InitialDirectory = "c:\\";
thisDialog.Filter = "(*.snoop, *.pcap, *.cap, *.net)|*.snoop; *.pcap; *.cap; *.net|" + "All files (*.*)|*.*";
thisDialog.FilterIndex = 1;
thisDialog.RestoreDirectory = false;
thisDialog.Multiselect = true; // Allow the user to select multiple files
thisDialog.Title = "Please Select Source File";
thisDialog.FileName = lastPath;
List<string> list = new List<string>();
if (thisDialog.ShowDialog() == DialogResult.OK)
{
foreach (String file in thisDialog.FileNames)
{
try
{
if ((myStream = thisDialog.OpenFile()) != null)
{
using (myStream)
{
listBoxFiles.Items.Add(file);
}
}
}
catch (Exception ex)
{
MessageBox.Show("Error: Could not read file from disk. Original error: " + ex.Message);
}
}
}
}
Save the last directory used in a global variable like this:
private string _lastPath = string.Empty;
then after the file selection initialize it:
if(thisDialog.Filenames.Length > 0)
_lastPath = Path.GetDirectoryName(thisDialog.Filenames[0]);
when you reopen the dialog set the InitialDirectory with this check:
thisDialog.InitialDirectory = (_lastPath.Length > 0 ? _lastPath: "c:\\");
and remove the thisDialog.FileName = lastPath;
EDIT --- UPDATE OF YOUR CODE ---
// This at the global level of your form
private string _lastPath = string.Empty;**
private void btnAdd_Click(object sender, EventArgs e)
{
System.IO.Stream myStream;
OpenFileDialog thisDialog = new OpenFileDialog();
thisDialog.InitialDirectory = (_lastPath.Length > 0 ? _lastPath: "c:\\");
thisDialog.Filter = "(*.snoop, *.pcap, *.cap, *.net)|*.snoop; *.pcap; *.cap; *.net|" + "All files (*.*)|*.*";
thisDialog.FilterIndex = 1;
thisDialog.RestoreDirectory = false;
thisDialog.Multiselect = true; // Allow the user to select multiple files
thisDialog.Title = "Please Select Source File";
thisDialog.FileName = lastPath;
List<string> list = new List<string>();
if (thisDialog.ShowDialog() == DialogResult.OK)
{
if(thisDialog.Filenames.Length > 0)
_lastPath = Path.GetDirectoryName(thisDialog.Filenames[0]);
foreach (String file in thisDialog.FileNames)
{
try
{
if ((myStream = thisDialog.OpenFile()) != null)
{
using (myStream)
{
listBoxFiles.Items.Add(file);
}
}
}
catch (Exception ex)
{
MessageBox.Show("Error: Could not read file from disk. Original error: " + ex.Message);
}
}
}
}
You can use a Visual Studio have the last path value for every execution of the application.
Only have to go to Project Properties->Configuration and add a value descriptor.
Example:
Name = LastPath; Type = string; Scope = User; Value = "Default path";
And then after you rebuild yout application, you can set this property this way:
Settings.Default.LastPath = LastPathSelected;
later, you can retrieve the value with:
thisDialog.InitialDirectory = Settings.Default.LastPath;
thisDialog.InitialDirectory = Path.GetDirectoryName(lastPath);
Yes, you can use the OpenFileDialog.InitialDirectory property. Note: you are setting the directory and not the file. So be sure to remove the filename from the path.
more info here
remove this line and you have the last path
thisDialog.InitialDirectory = "c:\\";
This is my encryption/decryption code. It works well but crashes when it encrypts a file even though it still encrypts it. Likewise, the program crashes when it decrypts a file even though it decrypts it.
After encryption or decryption the program gives the error 'unhandled exception has occurred in your application. It also says "the path is not of a legal form'.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Security;
using System.Security.Cryptography;
using System.Diagnostics;
using Microsoft.VisualBasic;
namespace Encryption_Decryption_Tool
{
public partial class frmMain : Form
{
string strFileToEncrypt, strFileToDecrypt, strOutputEncrypt, strOutputDecrypt;
System.IO.FileStream fsInput;
System.IO.FileStream fsOutput;
public frmMain()
{
InitializeComponent();
}
private byte[] CreateKey(string strPassword)
{
//Convert strPassword to an array and store in chrData.
char[] chrData = strPassword.ToCharArray();
//Use intLength to get strPassword size.
int intLength = chrData.GetUpperBound(0);
//Declare bytDataToHash and make it the same size as chrData.
byte[] bytDataToHash = new byte[intLength + 1];
//Use For Next to convert and store chrData into bytDataToHash.
for (int i = 0; i <= chrData.GetUpperBound(0); i++)
{
bytDataToHash[i] = Convert.ToByte(chrData[i]);
}
//Declare what hash to use.
System.Security.Cryptography.SHA512Managed SHA512 = new System.Security.Cryptography.SHA512Managed();
//Declare bytResult, Hash bytDataToHash and store it in bytResult.
byte[] bytResult = SHA512.ComputeHash(bytDataToHash);
//Declare bytKey(31). It will hold 256 bits.
byte[] bytKey = new byte[32];
//Use For Next to put a specific size (256 bits) of
//bytResult into bytKey. The 0 To 31 will put the first 256 bits
//of 512 bits into bytKey.
for (int i = 0; i <= 31; i++)
{
bytKey[i] = bytResult[i];
}
return bytKey;
//Return the key.
}
private byte[] CreateIV(string strPassword)
{
//Convert strPassword to an array and store in chrData.
char[] chrData = strPassword.ToCharArray();
//Use intLength to get strPassword size.
int intLength = chrData.GetUpperBound(0);
//Declare bytDataToHash and make it the same size as chrData.
byte[] bytDataToHash = new byte[intLength + 1];
//Use For Next to convert and store chrData into bytDataToHash.
for (int i = 0; i <= chrData.GetUpperBound(0); i++)
{
bytDataToHash[i] = Convert.ToByte(chrData[i]);
}
//Declare what hash to use.
System.Security.Cryptography.SHA512Managed SHA512 = new System.Security.Cryptography.SHA512Managed();
//Declare bytResult, Hash bytDataToHash and store it in bytResult.
byte[] bytResult = SHA512.ComputeHash(bytDataToHash);
//Declare bytIV(15). It will hold 128 bits.
byte[] bytIV = new byte[16];
//Use For Next to put a specific size (128 bits) of
//bytResult into bytIV. The 0 To 30 for bytKey used the first 256 bits.
//of the hashed password. The 32 To 47 will put the next 128 bits into bytIV.
for (int i = 32; i <= 47; i++)
{
bytIV[i - 32] = bytResult[i];
}
return bytIV;
//return the IV
}
private enum CryptoAction
{
//Define the enumeration for CryptoAction.
ActionEncrypt = 1,
ActionDecrypt = 2
}
private void EncryptOrDecryptFile(string strInputFile, string strOutputFile, byte[] bytKey, byte[] bytIV, CryptoAction Direction)
{
//In case of errors.
try
{
//Setup file streams to handle input and output.
fsInput = new System.IO.FileStream(strInputFile, FileMode.Open, FileAccess.Read);
fsOutput = new System.IO.FileStream(strOutputFile, FileMode.OpenOrCreate, FileAccess.Write);
fsOutput.SetLength(0);
//make sure fsOutput is empty
//Declare variables for encrypt/decrypt process.
byte[] bytBuffer = new byte[4097];
//holds a block of bytes for processing
long lngBytesProcessed = 0;
//running count of bytes processed
long lngFileLength = fsInput.Length;
//the input file's length
int intBytesInCurrentBlock = 0;
//current bytes being processed
CryptoStream csCryptoStream = null;
//Declare your CryptoServiceProvider.
System.Security.Cryptography.RijndaelManaged cspRijndael = new System.Security.Cryptography.RijndaelManaged();
//Setup Progress Bar
pbStatus.Value = 0;
pbStatus.Maximum = 100;
//Determine if ecryption or decryption and setup CryptoStream.
switch (Direction)
{
case CryptoAction.ActionEncrypt:
csCryptoStream = new CryptoStream(fsOutput, cspRijndael.CreateEncryptor(bytKey, bytIV), CryptoStreamMode.Write);
break;
case CryptoAction.ActionDecrypt:
csCryptoStream = new CryptoStream(fsOutput, cspRijndael.CreateDecryptor(bytKey, bytIV), CryptoStreamMode.Write);
break;
}
//Use While to loop until all of the file is processed.
while (lngBytesProcessed < lngFileLength)
{
//Read file with the input filestream.
intBytesInCurrentBlock = fsInput.Read(bytBuffer, 0, 4096);
//Write output file with the cryptostream.
csCryptoStream.Write(bytBuffer, 0, intBytesInCurrentBlock);
//Update lngBytesProcessed
lngBytesProcessed = lngBytesProcessed + Convert.ToInt64(intBytesInCurrentBlock);
//Update Progress Bar
pbStatus.Value = Convert.ToInt32((lngBytesProcessed / lngFileLength) * 100);
}
//Close FileStreams and CryptoStream.
csCryptoStream.Close();
fsInput.Close();
fsOutput.Close();
//If encrypting then delete the original unencrypted file.
if (Direction == CryptoAction.ActionEncrypt)
{
FileInfo fileOriginal = new FileInfo(strFileToEncrypt);
fileOriginal.Delete();
}
//If decrypting then delete the encrypted file.
if (Direction == CryptoAction.ActionDecrypt)
{
FileInfo fileEncrypted = new FileInfo(strFileToDecrypt);
fileEncrypted.Delete();
}
//Update the user when the file is done.
string Wrap = "\r\n";
if (Direction == CryptoAction.ActionEncrypt)
{
MessageBox.Show("Encryption Complete" + Wrap + Wrap + "Total bytes processed = " + lngBytesProcessed.ToString(), "Done", MessageBoxButtons.OK, MessageBoxIcon.Information);
//Update the progress bar and textboxes.
pbStatus.Value = 0;
txtFileToEncrypt.Text = "Click Browse to load file.";
txtPassEncrypt.Text = "";
txtConPassEncrypt.Text = "";
txtDestinationEncrypt.Text = "";
btnChangeEncrypt.Enabled = false;
btnEncrypt.Enabled = false;
}
else
{
//Update the user when the file is done.
MessageBox.Show("Decryption Complete" + Wrap + Wrap + "Total bytes processed = " + lngBytesProcessed.ToString(),"Done",MessageBoxButtons.OK,MessageBoxIcon.Information) ;
//Update the progress bar and textboxes.
pbStatus.Value = 0;
txtFileToDecrypt.Text = "Click Browse to load file.";
txtPassDecrypt.Text = "";
txtConPassDecrypt.Text = "";
txtDestinationDecrypt.Text = "";
btnChangeDecrypt.Enabled = false;
btnDecrypt.Enabled = false;
}
//Catch file not found error.
//if file not found
}
catch
{
MessageBox.Show("Please check to make sure the path and filename" + "are correct and if the file exists.", "Invalid Path or Filename", MessageBoxButtons.OK, MessageBoxIcon.Information);
//Catch all other errors. And delete partial files.
}
finally
{
fsInput.Close();
fsOutput.Close();
if (Direction == CryptoAction.ActionDecrypt)
{
FileInfo fileDelete = new FileInfo(txtDestinationDecrypt.Text);
fileDelete.Delete();
pbStatus.Value = 0;
txtPassDecrypt.Text = "";
txtConPassDecrypt.Text = "";
MessageBox.Show("Please check to make sure that you entered the correct" + "password.","Invalid Password", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
else
{
FileInfo fileDelete = new FileInfo(txtDestinationEncrypt.Text);
fileDelete.Delete();
pbStatus.Value = 0;
txtPassEncrypt.Text = "";
txtConPassEncrypt.Text = "";
MessageBox.Show("This file cannot be encrypted.", "File Cannot Be Encrypted", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
}
}
private void btnBrowseEncrypt_Click(object sender, EventArgs e)
{
//Setup the open dialog.
openFileDialog1.FileName = "";
openFileDialog1.Title = "Choose a file to encrypt";
openFileDialog1.InitialDirectory = "C:\\";
openFileDialog1.Filter = "All Files (*.*) | *.*";
//Find out if the user chose a file.
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
strFileToEncrypt = openFileDialog1.FileName;
txtFileToEncrypt.Text = strFileToEncrypt;
int iPosition = 0;
int i = 0;
//Get the position of the last "\" in the OpenFileDialog.FileName path.
//-1 is when the character your searching for is not there.
//IndexOf searches from left to right.
while (strFileToEncrypt.IndexOf('\\', i) != -1)
{
iPosition = strFileToEncrypt.IndexOf('\\', i);
i = iPosition + 1;
}
//Assign strOutputFile to the position after the last "\" in the path.
//This position is the beginning of the file name.
strOutputEncrypt = strFileToEncrypt.Substring(iPosition + 1);
//Assign S the entire path, ending at the last "\".
string S = strFileToEncrypt.Substring(0, iPosition + 1);
//Replace the "." in the file extension with "_".
strOutputEncrypt = strOutputEncrypt.Replace('.', '_');
//The final file name. XXXXX.encrypt
txtDestinationEncrypt.Text = S + strOutputEncrypt + ".encrypt";
//Update buttons.
btnEncrypt.Enabled = true;
btnChangeEncrypt.Enabled = true;
}
}
private void btnBrowseDecrypt_Click(object sender, EventArgs e)
{
//Setup the open dialog.
openFileDialog2.FileName = "";
openFileDialog2.Title = "Choose a file to decrypt";
openFileDialog2.InitialDirectory = "C:\\";
openFileDialog2.Filter = "Encrypted Files (*.encrypt) | *.encrypt";
//Find out if the user chose a file.
if (openFileDialog2.ShowDialog() == DialogResult.OK)
{
strFileToDecrypt = openFileDialog2.FileName;
txtFileToDecrypt.Text = strFileToDecrypt;
int iPosition = 0;
int i = 0;
//Get the position of the last "\" in the OpenFileDialog.FileName path.
//-1 is when the character your searching for is not there.
//IndexOf searches from left to right.
while (strFileToDecrypt.IndexOf('\\', i) != -1)
{
iPosition = strFileToDecrypt.IndexOf('\\', i);
i = iPosition + 1;
}
//strOutputFile = the file path minus the last 8 characters (.encrypt)
strOutputDecrypt = strFileToDecrypt.Substring(0, strFileToDecrypt.Length - 8);
//Assign S the entire path, ending at the last "\".
string S = strFileToDecrypt.Substring(0, iPosition + 1);
//Assign strOutputFile to the position after the last "\" in the path.
strOutputDecrypt = strOutputDecrypt.Substring((iPosition + 1));
//Replace "_" with "."
txtDestinationDecrypt.Text = S + strOutputDecrypt.Replace('_', '.');
//Update buttons
btnDecrypt.Enabled = true;
btnChangeDecrypt.Enabled = true;
}
}
private void btnChangeEncrypt_Click(object sender, EventArgs e)
{
//Setup up folder browser.
folderBrowserDialog1.Description = "Select a folder to place the encrypted file in.";
//If the user selected a folder assign the path to txtDestinationEncrypt.
if (folderBrowserDialog1.ShowDialog() == DialogResult.OK)
{
txtDestinationEncrypt.Text = folderBrowserDialog1.SelectedPath + "\\" + strOutputEncrypt + ".encrypt";
}
}
private void btnChangeDecrypt_Click(object sender, EventArgs e)
{
//Setup up folder browser.
folderBrowserDialog2.Description = "Select a folder for to place the decrypted file in.";
//If the user selected a folder assign the path to txtDestinationDecrypt.
if (folderBrowserDialog2.ShowDialog() == DialogResult.OK)
{
txtDestinationDecrypt.Text = folderBrowserDialog2.SelectedPath + "\\" + strOutputDecrypt.Replace('_', '.');
}
}
private void btnEncrypt_Click(object sender, EventArgs e)
{
//Make sure the password is correct.
if (txtConPassEncrypt.Text == txtPassEncrypt.Text)
{
//Declare variables for the key and iv.
//The key needs to hold 256 bits and the iv 128 bits.
byte[] bytKey = null;
byte[] bytIV = null;
//Send the password to the CreateKey function.
bytKey = CreateKey(txtPassEncrypt.Text);
//Send the password to the CreateIV function.
bytIV = CreateIV(txtPassEncrypt.Text);
//Start the encryption.
EncryptOrDecryptFile(strFileToEncrypt, txtDestinationEncrypt.Text, bytKey, bytIV, CryptoAction.ActionEncrypt);
}
else
{
MessageBox.Show ("Please re-enter your password.","Error",MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
txtPassEncrypt.Text = "";
txtConPassEncrypt.Text = "";
}
}
private void btnDecrypt_Click(object sender, EventArgs e)
{
//Make sure the password is correct.
if (txtConPassDecrypt.Text == txtPassDecrypt.Text)
{
//Declare variables for the key and iv.
//The key needs to hold 256 bits and the iv 128 bits.
byte[] bytKey = null;
byte[] bytIV = null;
//Send the password to the CreateKey function.
bytKey = CreateKey(txtPassDecrypt.Text);
//Send the password to the CreateIV function.
bytIV = CreateIV(txtPassDecrypt.Text);
//Start the decryption.
EncryptOrDecryptFile(strFileToDecrypt, txtDestinationDecrypt.Text, bytKey, bytIV, CryptoAction.ActionDecrypt);
}
else
{
MessageBox.Show ("Please re-enter your password.","Error",MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
txtPassDecrypt.Text = "";
txtConPassDecrypt.Text = "";
}
}
}
}
Copied exception from duplicate post:
************* Exception Text **************
System.ArgumentException: The path is not of a legal form.
at System.IO.Path.NormalizePathFast(String path, Boolean fullCheck)
at System.IO.FileInfo..ctor(String fileName)
at Encryption_Decryption_Tool.frmMain.EncryptOrDecryptFile(String strInputFile, String strOutputFile, Byte[] bytKey, Byte[] bytIV, CryptoAction Direction) in C:\Users\baffa\Documents\Visual Studio 2008\Projects\Encryption_Decryption_Tool\Encryption_Decryption_Tool\Form1.cs:line 236
at Encryption_Decryption_Tool.frmMain.btnEncrypt_Click(Object sender, EventArgs e) in C:\Users\baffa\Documents\Visual Studio 2008\Projects\Encryption_Decryption_Tool\Encryption_Decryption_Tool\Form1.cs:line 373
at System.Windows.Forms.Control.OnClick(EventArgs e)
at System.Windows.Forms.Button.OnMouseUp(MouseEventArgs mevent)
at System.Windows.Forms.Control.WmMouseUp(Message& m, MouseButtons button, Int32 clicks)
at System.Windows.Forms.Control.WndProc(Message& m)
at System.Windows.Forms.ButtonBase.WndProc(Message& m)
at System.Windows.Forms.Button.WndProc(Message& m)
at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
at System.Windows.Forms.NativeWindow.Callback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
Either your input or output file name is incorrect.
The way that you are processing the file names in the button click events is massive overkill and is what is likely causing the problems.
It would be much better to use the standard System.IO.Path methods.
Specifically, if you are just trying to take the selected file name and change the extension, all of your file name manipulation code can be replace with one line:
txtDestinationEncrypt.Text = System.IO.Path.ChangeExtension(openFileDialog1.FileName, ".encrypt");
Update
I have substantially cleaned up the EncryptOrDecryptFile code and verified that it works correctly in both directions. I have moved the module-level fsInput and fsOutput into this method and wrapped the primary players in using statements. I also moved the incorrect code in the finally area into the catch area, which is where it belongs. Finally, I also added checking to the beginning of the method to ensure a file is specified and that it is exists.
private void EncryptOrDecryptFile(string strInputFile, string strOutputFile, byte[] bytKey, byte[] bytIV, CryptoAction Direction)
{
//In case of errors.
try
{
if (string.IsNullOrEmpty(strInputFile))
{
MessageBox.Show("Please select an input file name", "Missing file name", MessageBoxButtons.OK, MessageBoxIcon.Information);
return;
}
if (!File.Exists(strInputFile))
{
MessageBox.Show(string.Format("The selected input file {0} does not exist.", strInputFile), "Invalid Path or Filename", MessageBoxButtons.OK, MessageBoxIcon.Information);
return;
}
if (string.IsNullOrEmpty(strOutputFile))
{
MessageBox.Show("Please select an output file name", "Missing file name", MessageBoxButtons.OK, MessageBoxIcon.Information);
return;
}
//holds a block of bytes for processing
long lngBytesProcessed = 0;
// Setup file streams to handle input and output.
using (var fsInput = new System.IO.FileStream(strInputFile, FileMode.Open, FileAccess.Read))
{
using (var fsOutput = new System.IO.FileStream(strOutputFile, FileMode.OpenOrCreate, FileAccess.Write))
{
//Declare your CryptoServiceProvider.
using (var cspRijndael = new System.Security.Cryptography.RijndaelManaged())
{
try
{
//Setup Progress Bar
pbStatus.Value = 0;
pbStatus.Maximum = 100;
cspRijndael.Key = bytKey;
cspRijndael.IV = bytIV;
ICryptoTransform oTransform = null;
// Determine if ecryption or decryption and setup transform.
switch (Direction)
{
case CryptoAction.ActionEncrypt:
oTransform = cspRijndael.CreateEncryptor();
break;
case CryptoAction.ActionDecrypt:
oTransform = cspRijndael.CreateDecryptor();
break;
default:
throw new Exception("Unknown Direction");
}
using (var csCryptoStream = new CryptoStream(fsOutput, oTransform, CryptoStreamMode.Write))
{
//Declare variables for encrypt/decrypt process.
byte[] bytBuffer = new byte[4097];
//running count of bytes processed
long lngFileLength = fsInput.Length;
//the input file's length
int intBytesInCurrentBlock = 0;
//Use While to loop until all of the file is processed.
while (lngBytesProcessed < lngFileLength)
{
//Read file with the input filestream.
intBytesInCurrentBlock = fsInput.Read(bytBuffer, 0, 4096);
//Write output file with the cryptostream.
csCryptoStream.Write(bytBuffer, 0, intBytesInCurrentBlock);
//Update lngBytesProcessed
lngBytesProcessed = lngBytesProcessed + Convert.ToInt64(intBytesInCurrentBlock);
//Update Progress Bar
pbStatus.Value = Convert.ToInt32((lngBytesProcessed / lngFileLength) * 100);
}
}
}
finally
{
if (cspRijndael != null)
{
// Clear the managed object
cspRijndael.Clear();
}
}
}
}
}
// If encrypting then delete the original unencrypted file.
if (Direction == CryptoAction.ActionEncrypt)
{
File.Delete(strFileToEncrypt);
}
// If decrypting then delete the encrypted file.
if (Direction == CryptoAction.ActionDecrypt)
{
File.Delete(strFileToDecrypt);
}
// Update the user when the file is done.
string Wrap = "\r\n";
if (Direction == CryptoAction.ActionEncrypt)
{
MessageBox.Show("Encryption Complete" + Wrap + Wrap + "Total bytes processed = " + lngBytesProcessed.ToString(), "Done", MessageBoxButtons.OK, MessageBoxIcon.Information);
//Update the progress bar and textboxes.
pbStatus.Value = 0;
txtFileToEncrypt.Text = "Click Browse to load file.";
txtPassEncrypt.Text = "";
txtConPassEncrypt.Text = "";
txtDestinationEncrypt.Text = "";
btnChangeEncrypt.Enabled = false;
btnEncrypt.Enabled = false;
}
else
{
//Update the user when the file is done.
MessageBox.Show("Decryption Complete" + Wrap + Wrap + "Total bytes processed = " + lngBytesProcessed.ToString(), "Done", MessageBoxButtons.OK, MessageBoxIcon.Information);
//Update the progress bar and textboxes.
pbStatus.Value = 0;
txtFileToDecrypt.Text = "Click Browse to load file.";
txtPassDecrypt.Text = "";
txtConPassDecrypt.Text = "";
txtDestinationDecrypt.Text = "";
btnChangeDecrypt.Enabled = false;
btnDecrypt.Enabled = false;
}
}
catch (Exception ex)
{
MessageBox.Show("Unknown exception occurred: " + ex.Message, "Unknown Exception", MessageBoxButtons.OK, MessageBoxIcon.Stop);
// Catch all other errors. And delete partial files.
if (Direction == CryptoAction.ActionDecrypt)
{
if (!string.IsNullOrEmpty(txtDestinationDecrypt.Text) && (File.Exists(txtDestinationDecrypt.Text)))
{
File.Delete(txtDestinationDecrypt.Text);
}
pbStatus.Value = 0;
txtPassDecrypt.Text = "";
txtConPassDecrypt.Text = "";
MessageBox.Show("Please check to make sure that you entered the correct password.", "Invalid Password", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
else
{
if (!string.IsNullOrEmpty(txtDestinationEncrypt.Text) && (File.Exists(txtDestinationEncrypt.Text)))
{
File.Delete(txtDestinationEncrypt.Text);
}
pbStatus.Value = 0;
txtPassEncrypt.Text = "";
txtConPassEncrypt.Text = "";
MessageBox.Show("This file cannot be encrypted.", "File Cannot Be Encrypted", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
}
}
I also modified the first part of each of the btnChange click events to verify that a file has been selected before this button is pressed:
private void btnChangeEncrypt_Click(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(strOutputEncrypt))
{
MessageBox.Show("Please select a file to encrypt first", "Select File", MessageBoxButtons.OK, MessageBoxIcon.Stop);
return;
}
and:
private void btnChangeDecrypt_Click(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(strOutputDecrypt))
{
MessageBox.Show("Please select a file to decrypt first", "Select File", MessageBoxButtons.OK, MessageBoxIcon.Stop);
return;
}