Question

I have been trying to make sense of this http://msdn.microsoft.com/en-us/library/sfezx97z.aspx which uses the SaveFileDialog, but it is hard for me to understand. I have the following code:

FileInfo existingFile = new FileInfo("C:\\Users\\cle1394\\Desktop\\Apple Foreign Tax Payment Sample Layout Proposed - Sample Data.xlsx");

ConsoleApplication2.Program.ExcelData data = ConsoleApplication2.Program.GetExcelData(existingFile);

var json = new JavaScriptSerializer().Serialize(data);

How can I output the contents of json to a .json or .txt file?

I would like to let the user either see a link/ button to click to download/ save the file to a location on their computer, or, simply display the save file dialog box so that they can save the file to a location on their computer.

EDIT (to let OP comment on what parts are not clear):

SaveFileDialog saveFileDialog1 = new SaveFileDialog();
saveFileDialog1.ShowDialog();
if(saveFileDialog1.FileName != "")
{
   File.WriteAllText(saveFileDialog1.FileName,json);   
}
Était-ce utile?

La solution

You are looking for this, then:

File.WriteAllText(@"c:\some\path\json.txt",json);

And note that it will save the file using UTF8-encoding without a Byte Order Mark. If you need the BOM, you need to use the File.WriteAllText(path, content, Enconding);

See here.

Update - adding sample with SaveFileDialog:

 if(!string.IsNullOrEmpty(saveFileDialog.FileName))
 {
     //saveFileDialog.FileName should contain the full path
     //according to the documentation: http://msdn.microsoft.com/en-us/library/system.windows.forms.filedialog.filename.aspx
     File.WriteAllText(saveFileDialog.FileName,json);

 }
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top