Problem writing a file from a Silverlight application - c#

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

Related

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

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.

c# Replace openfileDialog to a none gui stream

I am trying to separate the MIME gui from the code i need. I am almost there just one more gui element i dont know how to replace. This element is the openfiledialog. Here a code snippet.
Program.cs
var sfd = new OpenFileDialog();
sfd.FileName = "C:\\eml\\" + validOutputFilename;
try
{
var writer = new MimeMessageWriter();
using (var fs = sfd.OpenFile()) writer.Write(message, fs);
}
catch (Exception ex)
{
//ignore
// need to log
}
message is an IMessage. A class created to store the information about an eml file. The open file dialog is allowing you to put in the file name with an eml extension and that is all. write.Write expects an IMessage and a stream. Inside writer.Write the file is being written The only part of the file that uses this code is when the file itself is writen at the end and write out any attachments. Here are those code snippets.
*MimeMessageWriter
-the attachment uses it here
var embeddedMessage = attachment.OpenAsMessage();
var messageWriter = new MimeMessageWriter();
var msgStream = new MemoryStream();
messageWriter.Write(embeddedMessage, msgStream);
var messageAttachment = ew DotNetOpenMail.FileAttachment(msgStream.ToArray());
messageAttachment.ContentType = "message/rfc822";
messageAttachment.FileName = filename + ".eml";
outMessage.AddMixedAttachment(messageAttachment);
-write out the file part of the file
using (var sw = new StreamWriter(stream))
sw.Write(outMessage.ToDataString());
I want to replace openFileDialog with something that will allow me to pass the filename to write out file in the MimeMessageWriter
Replace
using (var fs = sfd.OpenFile()) writer.Write(message, fs);
with
string fileName = #"c:\eml\myAttachment.eml";
using ( FileStream fs = new FileStream( fileName, FileMode.CreateNew ) )
{
writer.Write( message, fs )
}
See also: http://msdn.microsoft.com/de-de/library/47ek66wy.aspx

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

Categories

Resources