Eugeny89
Eugeny89

Reputation: 3731

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.

Upvotes: 0

Views: 1070

Answers (2)

NKCSS
NKCSS

Reputation: 2746

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

Upvotes: 2

thmshd
thmshd

Reputation: 5847

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

Upvotes: 3

Related Questions