saveFileDialog generates 2 file instead 1? - c#

I do not understand why this generates 2 files instead of one:
have the same names, but one (that is ok) has the right extension (extension) and is xxxxBytes, while the other has no extension (file type is) and is 0Bytes.
Stream my1Stream;
SaveFileDialog saveFileDialog1 = new SaveFileDialog();
saveFileDialog1.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*";
saveFileDialog1.FilterIndex = 2;
saveFileDialog1.RestoreDirectory = true;
if (saveFileDialog1.ShowDialog() == DialogResult.OK)
{
if ((my1Stream = saveFileDialog1.OpenFile()) != null)
{
fileout = saveFileDialog1.FileName + extension;
passwordBytes = GetPasswordBytes();
my1Stream.Close();
AES.EncryptFile(filein, fileout, passwordBytes);
MessageBox.Show("File Criptato!");
}
}
the extension is derived from filein (in a OpenFileDialog) and declared in the form: private string extension :
filein = openFileDialog1.FileName;
extension = Path.GetExtension(filein);

From the MSDN page on SaveFileDialog.OpenFile method
For security purposes, this method creates a new file with the
selected name and opens it with read/write permissions. This can cause
unintentional loss of data if you select an existing file to save to
So this line
if ((my1Stream = saveFileDialog1.OpenFile()) != null)
creates a file with the name selected and with zero bytes. Then your code continues creating the file in the AES.Encryptfile call with tne name of fileOut
You could simply write
if (saveFileDialog1.ShowDialog() == DialogResult.OK)
{
fileout = saveFileDialog1.FileName;
passwordBytes = GetPasswordBytes();
AES.EncryptFile(filein, fileout, passwordBytes);
MessageBox.Show("File Criptato!");
}

The major part of your confusion is caused by the fact that you have the Explorer option "Hide extensions for known file types" enabled. Disable that immediately if you're working with files.
Furthermore, my1Stream = saveFileDialog1.OpenFile() actually creates the file, but you never write to my1Stream. That creates the first file, of 0 bytes, with the proper extension.
Then the following code:
fileout = saveFileDialog1.FileName + extension;
AES.EncryptFile(filein, fileout, passwordBytes);
Writes the second file, with a double extension.
If your AES library (or wherever you copied AES.EncryptFile() from) doesn't support writing to streams, simply remove the if ((my1Stream = saveFileDialog1.OpenFile()) != null) and the extension stuff. The SaveFileDialog.FileName does include the extension:
if (saveFileDialog1.ShowDialog() == DialogResult.OK)
{
fileout = saveFileDialog1.FileName;
passwordBytes = GetPasswordBytes();
AES.EncryptFile(filein, fileout, passwordBytes);
MessageBox.Show("File Criptato!");
}

Related

Opening a File in C# using FileStream

I am trying to open a Binary file that I plan on converting to hex but I am running into issues with reading the file via FileStream,
private void button1_Click(object sender, EventArgs e)
{
openFD.Title = "Insert a BIN file";
openFD.InitialDirectory = "C:"; // Chooses the default location to open the file
openFD.FileName = " "; // Iniitalizes the File name
openFD.Filter = "Binary File|*.bin|Text File|*.txt"; // FIlters the types of files allowed to by chosen
if (openFD.ShowDialog() != DialogResult.Cancel)
{
chosenFile = openFD.FileName;
string directoryPath = Path.GetDirectoryName(chosenFile); // Returns the directory and the file name to reference the file
string dirName = System.IO.Path.GetDirectoryName(openFD.FileName); // Returns the proper directory with which to refernce the file
richTextBox1.Text += dirName;
richTextBox1.Text += chosenFile;
FileStream InputBin = new FileStream(
directoryPath, FileMode.Open, FileAccess.Read, FileShare.None);
}
}
I am receiving an error saying that the access to the path is denied, any ideas?
Now that I have gotten that error taken care of I have ran into another Issue, I can read the binary file, but I want to display it as a Hex file, I'm not sure what I am doing wrong but I'm not getting an output in HEX, it seems to be Int values...
if (openFD.ShowDialog() != DialogResult.Cancel)
{
chosenFile = openFD.FileName;
string directoryPath = Path.GetDirectoryName(chosenFile);
string dirName = System.IO.Path.GetDirectoryName(openFD.FileName);
using (FileStream stream = new FileStream(chosenFile, FileMode.Open, FileAccess.Read))
{
size = (int)stream.Length;
data = new byte[size];
stream.Read(data, 0, size);
}
while (printCount < size)
{
richTextBox1.Text += data[printCount];
printCount++;
}
Your code is miscommented
string directoryPath = Path.GetDirectoryName(chosenFile); // Returns the directory and the file name to reference the file
is not the filename, it's the directory path. You want:
FileStream InputBin = new FileStream(chosenFile, FileMode.Open,FileAccess.Read, FileShare.None);
Addtionally, if I were to guess based on your intentions, you should update your full function to be:
private void button1_Click(object sender, EventArgs e)
{
openFD.Title = "Insert a BIN file";
openFD.InitialDirectory = "C:"; // Chooses the default location to open the file
openFD.FileName = " "; // Iniitalizes the File name
openFD.Filter = "Binary File|*.bin|Text File|*.txt"; // FIlters the types of files allowed to by chosen
if (openFD.ShowDialog() != DialogResult.Cancel)
{
chosenFile = openFD.FileName;
richTextBox1.Text += chosenFile; //You may want to replace this with = unless you mean to append something that is already there.
FileStream InputBin = new FileStream(chosenFile, FileMode.Open,FileAccess.Read, FileShare.None);
}
}
To answer your second quesiton:
I am receiving an error saying that the access to the path is denied,
any ideas?
Now that I have gotten that error taken care of I have ran into
another Issue, I can read the binary file, but I want to display it as
a Hex file, I'm not sure what I am doing wrong but I'm not getting an
output in HEX, it seems to be Int values...
Modify to use string.Format:
if (openFD.ShowDialog() != DialogResult.Cancel)
{
chosenFile = openFD.FileName;
string directoryPath = Path.GetDirectoryName(chosenFile);
string dirName = System.IO.Path.GetDirectoryName(openFD.FileName);
using (FileStream stream = new FileStream(chosenFile, FileMode.Open, FileAccess.Read))
{
size = (int)stream.Length;
data = new byte[size];
stream.Read(data, 0, size);
}
while (printCount < size)
{
richTextBox1.Text += string.Format( "{0:X} ", data[printCount];
printCount++;
}
}
I've included an ideone example.

How to save image to selected path from Stream object

The following code prompts the user to select a path to save an image from the pictureBox:
Stream myStream;
SaveFileDialog saveFileDialog1 = new SaveFileDialog();
saveFileDialog1.Filter = "Portable Network Graphics|*.png";
saveFileDialog1.Title = "Bild speichern";
saveFileDialog1.RestoreDirectory = true;
saveFileDialog1.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
if (saveFileDialog1.ShowDialog() == DialogResult.OK)
{
if ((myStream = saveFileDialog1.OpenFile()) != null)
{
this.picBox.Image.Save(myStream.ToString()); // is not getting the selected path
myStream.Close();
}
}
But how can I get the path from myStream or save the image to the user defined location (with compatibility to .NET 3.5)?
If you want to get the selected file path from the save dialog then use...
saveFileDialog1.FileName;
See here for more information on this property
You don't need to worry about using a Stream for this task.
Just to be clear, here is what your code should be...
SaveFileDialog saveFileDialog1 = new SaveFileDialog();
saveFileDialog1.Filter = "Portable Network Graphics|*.png";
saveFileDialog1.Title = "Bild speichern";
saveFileDialog1.RestoreDirectory = true;
saveFileDialog1.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
if (saveFileDialog1.ShowDialog() == DialogResult.OK)
{
this.picBox.Image.Save(saveFileDialog1.FileName);
}
you can work with the SaveFileDialog.FileName only, no need for separated streams, try this:
using (var saveFileDialog1 = new SaveFileDialog())
{
saveFileDialog1.Filter = "Portable Network Graphics|*.png";
saveFileDialog1.Title = "Bild speichern";
saveFileDialog1.RestoreDirectory = true;
saveFileDialog1.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
if (saveFileDialog1.ShowDialog() == DialogResult.OK)
{
picBox.Image.Save(saveFileDialog1.FileName);
}
}
You can use:
string path = Path.GetDirectory(saveFileDialog1.Filename);
this.picBox.Image.Save(saveFileDialog1.Filename);
You really don't need a stream to do that :)
How's this?
SaveFileDialog saveFileDialog1 = new SaveFileDialog();
saveFileDialog1.Filter = "Portable Network Graphics|*.png";
saveFileDialog1.Title = "Bild speichern";
saveFileDialog1.RestoreDirectory = true;
saveFileDialog1.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
if (saveFileDialog1.ShowDialog() == DialogResult.OK)
{
(using FileStream fStr = new FileStream(saveFileDialog1.FileName, FileMode.Create))
{
this.picBox.Image.Save(fStr);
fStr.Close();
}
}

Read the entire file into a byte array in WINFORMS

I want to read the content of the file opened using file dialog box and then save it in a byte array to pass it to a web service
Stream myStream;
OpenFileDialog saveFileDialog1 = new OpenFileDialog();
saveFileDialog1.Filter = "zip files (*.zip)|*.zip|All files (*.*)|*.*";
saveFileDialog1.FilterIndex = 2;
saveFileDialog1.RestoreDirectory = true;
if (saveFileDialog1.ShowDialog() == DialogResult.OK)
{
if ((myStream = saveFileDialog1.OpenFile()) != null)
{
NSITESERVICE.UploadSoapClient obj = new NSITESERVICE.UploadSoapClient();
byte[] filebytes = //what should i pass it over here...
obj.UploadFile("kamal", "p#ssword", filebytes);
// Code to write the stream goes here.
myStream.Close();
}
}
I dont know where i am wrong
Any help is appreciated. Thnaks
You are not assigning anything to filebytes variable so you are essentially passing null to the service. Use File.ReadAllBytes method to read all the bytes and pass it to the webservice.
You're not actually reading the bytes out of the myStream.
byte[] fileBytes = new byte[myStream.Length];
myStream.Read(fileBytes,0,mystream.Length);
obj.UploadFile(...)

Problem writing a file from a Silverlight application

Look at the following code (it's a part of Silverlight app):
SaveFileDialog dialog = new SaveFileDialog();
dialog.Filter = "JSON Files|*.json|All Files (*.*)|*.*";
dialog.DefaultExt = "json";
if (dialog.ShowDialog() == true) {
string filename = dialog.SafeFileName;
System.IO.StreamWriter sw =
new System.IO.StreamWriter(new FileStream(filename,FileMode.Create));
sw.Write("string");
sw.Flush();
sw.Close();
}
It works (creates file and writes "string" there) on the developer machine, but does nothing on my machine, the file isn't created at all.
Any ideas what it can be?! Thank you in advance!
P.S. We tried removing the sw.Flush(); and that did not help. Also we tried to set autoflush to true - didn't help as well. Changing FileMode.Create to FileMode.Append has no effect too.
Try this:
SaveFileDialog dialog = new SaveFileDialog();
dialog.Filter = "JSON Files|*.json|All Files (*.*)|*.*";
dialog.DefaultExt = "json";
if (dialog.ShowDialog() == true) {
System.IO.StreamWriter sw = new System.IO.StreamWriter(( Stream )dialog.OpenFile());
sw.Write("string");
sw.Close();
}
It's a security problem, you need to use the filestream that is returned by the SaveFileDialog. Use it to open the stream and write.
SaveFileDialog.OpenFile()

Ado.net image operation

In my C# winform app. I connected my program to the MS SQL Server 2005 successfully, now I want to add a new column of type Image, how can I Insert the Image in the DB and get it back? and in our Business Logic Class which data type variable we will declare?
how can I Insert the Image in the DB and get it back?
you need to get the image in bytes as shown in below code
Edited Code Example
private void BrowseImage(object o)
{
OpenFileDialog openFileDialog = new OpenFileDialog();
// Set filter for file extension and default file extension
//openFileDialog.DefaultExt = ".bmp";
//openFileDialog.Filter = "24-Bit Bitmap (.bmp)|*.bmp";
openFileDialog.InitialDirectory = #"C://"
openFileDialog.DefaultExt = ".jpg";
openFileDialog.Filter =
"BMP (*.BMP)|*.BMP|" +
"JPEG (*.JPG; *.JPEG; *.JPE)|*.JPG;*JPEG|" +
"GIF (*.GIF)|*.GIF|" +
"TIFF (*.TIFF)|*.TIFF|" +
"PNG (*.PNG)|*.PNG|" +
"DIB (*.DIB)|*.DIB|" +
"JFIF (*.JFIF)|*.JFIF";
// Display OpenFileDialog by calling ShowDialog method
Nullable<bool> result = openFileDialog.ShowDialog();
// Get the selected file name and display in a TextBox
if (result == true)
{
// Open document
string filename = openFileDialog.FileName;
Stream stream = openFileDialog.OpenFile();
byte[] bytes = null;
if (stream != null && stream.CanRead)
{
bytes = new byte[stream.Length];
stream.Read(bytes, 0, Convert.ToInt32(stream.Length));
stream.Close();
}
}
}
in our Business Logic Class which data type variable we will declare?
you need to define the image property as Byte[] and assign this property with the bytes[] got above.

Categories

Resources