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(...)
Related
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!");
}
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.
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.
}
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()
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.