Opening a File in C# using FileStream - c#

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.

Related

decrypt pgp files from a folder and moving it - c#

I am trying to decrypt .pgp files from a location and then moving those files to another location. I looked into this article and code accordingly. In my code I am developing an application which will check to a certain location after every 100 seconds and if there are files then it will decrypt and move. but I am getting this exception The process cannot access the file 'c:\file.pgp' because it is being used by another process.
Here is my code where I am calling that class which I copied from that article.
private static void OnTimedEvent(object source, ElapsedEventArgs e)
{
//Do the stuff you want to be done every hour;
string sourcePath = #"files location";
string archivePath = #"move original file after decrypting location";
string targetPath = #"decrypted file location";
string pubkeyPath = #"public key location\PGPPublicKey.txt";
string privkeyPath = #"private key location\PGPPrivateKey.txt";
string fileName = "";
string destFile = "";
if (System.IO.Directory.Exists(sourcePath))
{
string[] files = System.IO.Directory.GetFiles(sourcePath);
// Copy the files and overwrite destination files if they already exist.
foreach (string s in files)
{
PGPDecrypt test = new PGPDecrypt(s,
privkeyPath,
"password",
targetPath + "decrypted.txt",
pubkeyPath);
FileStream fs = File.Open(s, FileMode.Open);
test.decrypt(fs, targetPath + "decrypted.txt");
// Use static Path methods to extract only the file name from the path.
fileName = System.IO.Path.GetFileName(s);
destFile = System.IO.Path.Combine(archivePath, fileName);
System.IO.File.Move(s, archivePath);
}
}
}
Where are you getting the error. If you are getting error while moving it might be because your filestream is not close. After decryption and before move close the filestream with fs.Close();
I believe the issue you are having is caused by the file not being closed, when you loop with the foreach loop the first iteration probably works. However, the next time, because it was never closed, it is still being used.
Try adding
fs.Close();
At the end of the foreach loop
This is I ended up and it is working
//Decrypt
using DidiSoft.Pgp;
PGPLib pgp = new PGPLib();
string inputFileLocation = file Location;
string privateKeyLocation = #"I posted my private at this location";
string privateKeyPassword = "Decryption Password";
string outputFile = #"Output Location";
// decrypt and obtain the original file name
// of the decrypted file
string originalFileName =
pgp.DecryptFile(inputFileLocation,
privateKeyLocation,
privateKeyPassword,
outputFile);
//Move decrypted file to archive
string path = Decrypted file Location;
string path2 = #"Archive file location" + Path.GetFileName(file); ;
try
{
if (!File.Exists(path))
{
// This statement ensures that the file is created,
// but the handle is not kept.
using (FileStream fs = File.Create(path)) { }
}
// Ensure that the target does not exist.
if (File.Exists(path2))
File.Delete(path2);
// Move the file.
File.Move(path, path2);
}
catch (Exception e)
{
}

Exception before a wcf transfer file

I used this example and my code is
private void dialogBtn_Click(object sender, EventArgs e)
{
string file;
DialogResult result = openFileDialog1.ShowDialog(); // Show the dialog.
if (result == DialogResult.OK) // Test result.
{
file = openFileDialog1.FileName;
System.IO.FileInfo fileInfo = new System.IO.FileInfo(file);
TransferServiceClient clientUpload = new TransferServiceClient();
RemoteFileInfo uploadRequestInfo = new RemoteFileInfo();
using (System.IO.FileStream stream = new System.IO.FileStream(file, System.IO.FileMode.Open, System.IO.FileAccess.Read))
{
uploadRequestInfo.FileName = file;
uploadRequestInfo.Length = fileInfo.Length;
uploadRequestInfo.FileByteStream = stream;
//clientUpload.UploadFile(uploadRequestInfo);
clientUpload.UploadFile(fileInfo.Name, fileInfo.Length, stream);
}
}
}
During the clientUpload.UploadFile(fileInfo.Name, fileInfo.Length, stream); I receive an error
An unhandled exception of type 'System.ServiceModel.FaultException`1' occurred in mscorlib.dll
Additional information: Could not find a part of the path 'C:\upload\Book1.xlsx'.
But, the Book1.xlsx is not inside upload folder. It's at the Desktop.
Well, the service implementation of the UploadFile method in the example is as follows:
public void UploadFile(RemoteFileInfo request)
{
FileStream targetStream = null;
Stream sourceStream = request.FileByteStream;
string uploadFolder = #"C:\upload\";
string filePath = Path.Combine(uploadFolder, request.FileName);
using (targetStream = new FileStream(filePath, FileMode.Create,
FileAccess.Write, FileShare.None))
{
//read from the input stream in 65000 byte chunks
const int bufferLen = 65000;
byte[] buffer = new byte[bufferLen];
int count = 0;
while ((count = sourceStream.Read(buffer, 0, bufferLen)) > 0)
{
// save to output stream
targetStream.Write(buffer, 0, count);
}
targetStream.Close();
sourceStream.Close();
}
}
Note the line
string uploadFolder = #"C:\upload\";
You need to change that to some existing folder where you want the uploaded files to be stored.

Prompt for Saving File to Disk

Actually, I have saved a file in BinaryData in Sql and now I am able to download that file by converting the BinaryData into Bytes.
My code is :
object value = (sender as DevExpress.Web.ASPxGridView.ASPxGridView).GetRowValues(e.VisibleIndex, "ID");
Int64 FileID = Convert.ToInt64(value);
var filedata = (from xx in VDC.SURVEY_QUESTION_REPLIES
where xx.ID == FileID
select xx).FirstOrDefault();
string fileextension = filedata.FILE_EXTENSION.ToString();
string fileName = filedata.ANSWER_TEXT.ToString() + fileextension;
string DocumentName = null;
FileStream FStream = null;
BinaryWriter BWriter = null;
byte[] Binary = null;
const int ChunkSize = 100;
int SizeToWrite = 0;
MemoryStream MStream = null;
DocumentName = fileName;
FStream = new FileStream(#"c:\\" + DocumentName, FileMode.OpenOrCreate, FileAccess.Write);
BWriter = new BinaryWriter(FStream);
Binary = (filedata.FILE_DATA) as byte[];
SizeToWrite = ChunkSize;
MStream = new MemoryStream(Binary);
for (int i = 0; i < Binary.GetUpperBound(0) - 1; i = i + ChunkSize)
{
if (i + ChunkSize >= Binary.Length) SizeToWrite = Binary.Length - i;
byte[] Chunk = new byte[SizeToWrite];
MStream.Read(Chunk, 0, SizeToWrite);
BWriter.Write(Chunk);
BWriter.Flush();
}
BWriter.Close();
FStream.Close();
FStream.Dispose();
System.Diagnostics.Process.Start(#"c:\" + DocumentName);
and it is directly saving the file to the location C Drive.
Now,My Requirement is that,I need to get a Prompt for saving that file and user need to select the location of saving.
Is that Possible ?
You create a filestream with a fixed location here:
FStream = new FileStream(#"c:\\" + DocumentName, FileMode.OpenOrCreate, FileAccess.Write);
What you would have to do is something like this:
var dialog = new SaveFileDialog();
if (dialog.ShowDialog() == DialogResult.OK)
{
FStream = new FileStream(dialog.FileName, FileMode.OpenOrCreate, FileAccess.Write);
// put the rest of your file saving code here
}
Remember to import the Forms namespace
using System.Windows.Forms;
If its Forms app You can use SaveFileDialog class
it is possible,
you can use a saveFileDialog that you create in your designer and call the "show" method to open that dialog :
private void button1_Click(object sender, System.EventArgs e)
{
Stream myStream ;
SaveFileDialog saveFileDialog1 = new SaveFileDialog();
saveFileDialog1.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*" ;
saveFileDialog1.FilterIndex = 2 ;
saveFileDialog1.RestoreDirectory = true ;
if(saveFileDialog1.ShowDialog() == DialogResult.OK)
{
if((myStream = saveFileDialog1.OpenFile()) != null)
{
// Code to write the stream goes here.
myStream.Close();
}
}
}
Source : http://msdn.microsoft.com/en-gb/library/system.windows.forms.savefiledialog.aspx
I see that you use web components of DevExpress, so assuming that you want to send the stream to response for the client to save the file.
If it is an ASP.NET MVC application, you can return FileContentResult as action result directly. Otherwise, you might use the following sample adapting into your code
Response.ContentType = "application/octet-stream";
Response.AddHeader("Content-Disposition", "attachment; filename=" + DocumentName);
MStream.WriteTo(Response.OutputStream);
Depending on user's browser settings, save file dialog might be shown to the user.

Convert file received from jquery to byte array

I need help in converting a file received from a jquery ajax to byte array. I'm using a plugin called ajaxfileupload then from a jquery ajax call I send a file from a fileupload control to a handler. Here is my
handler code:
if (context.Request.Files.Count > 0)
{
string path = context.Server.MapPath("~/Temp");
if (!Directory.Exists(path))
Directory.CreateDirectory(path);
var file = context.Request.Files[0];
string fileName;
if (HttpContext.Current.Request.Browser.Browser.ToUpper() == "IE")
{
string[] files = file.FileName.Split(new char[] { '\\' });
fileName = files[files.Length - 1];
}
else
{
fileName = file.FileName;
}
string fileType = file.ContentType;
string strFileName = fileName;
FileStream fs = new FileStream("~/Temp/" + strFileName, FileMode.Open, FileAccess.Read);
BinaryReader br = new BinaryReader(fs);
Byte[] imagebytes = br.ReadBytes((Int32)fs.Length);
br.Close();
fs.Close();
DBAccess dbacc = new DBAccess();
dbacc.saveImage(imagebytes);
string msg = "{";
msg += string.Format("error:'{0}',\n", string.Empty);
msg += string.Format("msg:'{0}'\n", strFileName);
msg += "}";
context.Response.Write(msg);
}
I'm saving the file to a folder within a project then trying to retrieve that file and save it to the database. I can assure you that the image is being saved to the temp folder. The problem is with the line with (*) the file path is wrong. This is the file path that is being retrieved. "'C:\Program Files\Common Files\Microsoft Shared\DevServer\10.0\~\Temp\2012-06-03 01.25.47.jpg'.". The temp folder is located locally inside my project and I want to retrieved the image within that folder. How can I set the file path to my desired location? Or is there another way to convert a file to byte array after retrieving it from a jquery ajax call?
Credits to these articles:
Save and Retrieve Files from SQL Server Database using ASP.NET
Async file upload with jQuery and ASP.NET
Just these 3 lines will do:
int filelength = file.ContentLength;
byte[] imagebytes = new byte[filelength ];
file.InputStream.Read(imagebytes , 0, filelength );
using (var stream = upload.InputStream)
{
// use stream here: using StreamReader, StreamWriter, etc.
}

How to open file .txt with using openFileDialog in c#?

I have to open and read from a .txt file, here is the code I'm using:
Stream myStream;
openFileDialog1.FileName = string.Empty;
openFileDialog1.InitialDirectory = "F:\\";
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
var compareType = StringComparison.InvariantCultureIgnoreCase;
var fileName = Path.GetFileNameWithoutExtension(openFileDialog1.FileName);
var extension = Path.GetExtension(openFileDialog1.FileName);
if (extension.Equals(".txt", compareType))
{
try
{
using (myStream = openFileDialog1.OpenFile())
{
string file = Path.GetFileName(openFileDialog1.FileName);
string path = Path.GetFullPath(file); //when i did it like this it's work fine but all the time give me same path whatever where my "*.txt" file is
//Insert code to read the stream here.
//fileName = openFileDialog1.FileName;
StreamReader reader = new StreamReader(path);
MessageBox.Show(file, "fileName");
MessageBox.Show(path, "Directory");
}
}
// Exception thrown: Empty path name is not legal
catch (ArgumentException ex)
{
MessageBox.Show("Error: Could not read file from disk. " +
"Original error: " + ex.Message);
}
}
else
{
MessageBox.Show("Invaild File Type Selected");
}
}
The code above throws an exception which says "Empty path name is not legal".
What am I doing wrong?
As pointed by hmemcpy, your problem is in the following lines
using (myStream = openFileDialog1.OpenFile())
{
string file = Path.GetFileName(openFileDialog1.FileName);
string path = Path.GetDirectoryName(file);
StreamReader reader = new StreamReader(path);
MessageBox.Show(file, "fileName");
MessageBox.Show(path, "Directory");
}
I'm going to break down for you:
/*
* Opend the file selected by the user (for instance, 'C:\user\someFile.txt'),
* creating a FileStream
*/
using (myStream = openFileDialog1.OpenFile())
{
/*
* Gets the name of the the selected by the user: 'someFile.txt'
*/
string file = Path.GetFileName(openFileDialog1.FileName);
/*
* Gets the path of the above file: ''
*
* That's because the above line gets the name of the file without any path.
* If there is no path, there is nothing for the line below to return
*/
string path = Path.GetDirectoryName(file);
/*
* Try to open a reader for the above bar: Exception!
*/
StreamReader reader = new StreamReader(path);
MessageBox.Show(file, "fileName");
MessageBox.Show(path, "Directory");
}
What you should do is to cahnge the code to something like
using (myStream = openFileDialog1.OpenFile())
{
// ...
var reader = new StreamReader(myStream);
// ...
}
You want user to select only .txt files?
Then use the .Filter property, like that:
openFileDialog1.Filter = "txt files (*.txt)|*.txt";
Your bug is in the lines:
string file = Path.GetFileName(openFileDialog1.FileName);
string path = Path.GetDirectoryName(file);
In the first line the file variable will only contain the file name, e.g. MyFile.txt, making the second line return an empty string to the path variable. Further down your code you'll attempt to create a StreamReader with an empty path, and this what throws the exception.
By the way, this is exactly what the exception tells you. If you remove the try..catch around the using block, you would've seen it happen during debug in your Visual Studio.
StreamReader accepts Stream type of object while you are passing it a string.
try this,
Stream myStream;
using (myStream = openFileDialog1.OpenFile())
{
string file = Path.GetFileName(openFileDialog1.FileName);
string file2 = Path.GetFileNameWithoutExtension(openFileDialog1.FileName);
string path = Path.GetDirectoryName(openFileDialog1.FileName);
StreamReader reader = new StreamReader(myStream);
while (!reader.EndOfStream)
{
MessageBox.Show(reader.ReadLine());
}
MessageBox.Show(openFileDialog1.FileName.ToString());
MessageBox.Show(file, "fileName");
MessageBox.Show(path, "Directory");
}

Categories

Resources