How to save image to selected path from Stream object - c#

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();
}
}

Related

How to save a report directly to .doc?

I have a report and i want to save it directly without a dialog.
Here is my code until now
SaveFileDialog saveFileDialog = new SaveFileDialog();
saveFileDialog.InitialDirectory = #"C:\temp";
saveFileDialog.RestoreDirectory = true;
saveFileDialog.Title = "Browse Text Files";
saveFileDialog.DefaultExt = "doc";
saveFileDialog.Filter = "Word Doc (*.doc)|*.doc|PDF (*.pdf)| *.pdf";
saveFileDialog.CheckFileExists = false;
saveFileDialog.CheckPathExists = true;
Warning[] warnings;
string[] streams;
string mimeType;
string encoding;
string extension;
byte[] bytes = reportTest.LocalReport.Render("Word", null, out mimeType, out encoding, out extension, out streams, out warnings);
//if (saveFileDialog.ShowDialog() == DialogResult.OK)
//{
saveFileDialog.FileName = "123.doc";
var filename = saveFileDialog.FileName;
System.IO.FileStream file = new FileStream(filename, FileMode.Create);
file.Write(bytes, 0, bytes.Length);
file.Close();
//}
Can someone help me how to save the file directly to c:\temp\123.doc (without dialog in the explorer).
Thanks a lot!
You can directly save this with path and file name
filename="PATH" + "test.doc";
System.IO.FileStream file = new FileStream(filename, FileMode.Create);

saveFileDialog generates 2 file instead 1?

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

Writing MemoryStream into SaveAs Dialogue Box in WInform

I have an image which i want to write into itext Pdf file using c#.Here is my code to generate image from chart and write into itext pdf file.
Document pdfDoc = new Document(PageSize.A4, 10f, 10f, 10f, 0f);
using (MemoryStream stream = new MemoryStream())
{
pdfDoc.Open();
pieChart.SaveImage(stream, ChartImageFormat.Png);
iTextSharp.text.Image chartImage = iTextSharp.text.Image.GetInstance(stream.GetBuffer());
chartImage.ScalePercent(75f);
pdfDoc.Add(chartImage);
}
pdfDoc.Close();
Now as per my reuirement i have to open this pdf file using Save as dialogue box.Here is the code by which i an trying to open this pdf file..
Stream myStream;
SaveFileDialog saveFileDialog1 = new SaveFileDialog();
saveFileDialog1.Filter = "Pdf files (*.pdf)|*.pdf|All files (*.*)|*.*";
saveFileDialog1.FilterIndex = 0;
saveFileDialog1.RestoreDirectory = true;
if (saveFileDialog1.ShowDialog() == DialogResult.OK)
{
if ((myStream = saveFileDialog1.OpenFile()) != null)
{
// Code to write the stream goes here.
PdfWriter.GetInstance(pdfDoc, myStream);
myStream.Close();
}
}
But i am not able to get the pdf file.Dialogue Box is coming but i am not able to get the pdf file.
Please help me to resolve the issue .
Thanks in advance.
you need to save ur streambytes data to a file ...
Stream myStream;
SaveFileDialog saveFileDialog1 = new SaveFileDialog();
saveFileDialog1.Filter = "Pdf files (*.pdf)|*.pdf|All files (*.*)|*.*";
saveFileDialog1.FilterIndex = 0;
saveFileDialog1.RestoreDirectory = true;
if (saveFileDialog1.ShowDialog() == DialogResult.OK)
{
if ((myStream = saveFileDialog1.OpenFile()) != null)
{
// Code to write the stream goes here.
PdfWriter.GetInstance(pdfDoc, myStream);
myStream.Close();
using (FileStream file = new FileStream(saveFileDialog1.FileName, FileMode.Create, System.IO.FileAccess.Write,FileShare.ReadWrite)) {
byte[] bytes = new byte[myStream.Length];
ms.Read(bytes, 0, (int)myStream.Length);
file.Write(bytes, 0, bytes.Length);
myStream.Close();
}
}
}
you can write stream data using streamwriter...

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.

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()

Categories

Resources