简体   繁体   English

在WPF C#中编写JSON(或TXT)文件

[英]Writing a JSON (or TXT) file in WPF C#

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. 我一直试图理解这个使用SaveFileDialog的http://msdn.microsoft.com/en-us/library/sfezx97z.aspx ,但我很难理解。 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? 如何将json的内容输出到.json.txt文件?

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): 编辑(让OP评论哪些部分不清楚):

SaveFileDialog saveFileDialog1 = new SaveFileDialog();
saveFileDialog1.ShowDialog();
if(saveFileDialog1.FileName != "")
{
   File.WriteAllText(saveFileDialog1.FileName,json);   
}

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. 请注意,它将使用UTF8编码保存文件,而不使用字节顺序标记。 If you need the BOM, you need to use the File.WriteAllText(path, content, Enconding); 如果需要BOM,则需要使用File.WriteAllText(path, content, Enconding);

See here. 看这里。

Update - adding sample with SaveFileDialog: 更新 - 使用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);

 }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM