您好我想在MVC中创建文件并将JSON数据插入该文件中。 用于创建该文件的文件夹位置是
〜/内容/文件
请提出任何建议
答案 0 :(得分:2)
public FileResult SaveJsonDataToFile(string JsonString)
{
#region " Set Path of File "
// ASP.NET MVC4
string FilePath = HttpContext.Server.MapPath("~/Content/File/jsondata.json");
// ASP.NET MVC1 -> MVC3
// use this HttpContext.Current.Server.MapPath("~/Content/File/jsondata.json");
// Ref : http://stackoverflow.com/questions/1268738/asp-net-mvc-find-absolute-path-to-the-app-data-folder-from-controller
#endregion
#region " Save Data to File "
using (System.IO.StreamWriter FWriter = new StreamWriter(FilePath, true))
{
FWriter.Write(JsonString);
}
#endregion
#region " Read File to FileData "
byte[] FileData = null;
FileData = System.IO.File.ReadAllBytes(FilePath);
#endregion
#region " Delete File "
if (System.IO.File.Exists(FilePath))
System.IO.File.Delete(FilePath);
#endregion
// return if you need to send file to client
return File(FileData, "text/json" /* i don't sure for json file mimetype */);
}
此示例代码为C#.Net MVC
希望这有帮助!答案 1 :(得分:0)
试试这个......
public class Countries {
public string Country { get; set; }
public string CountryCode { get; set; }
public string Currency { get; set; }
public string CurrencyCode { get; set; }
}
List < Countries > _country = new List < Countries > ();
_country.Add(new Countries() Country = "Pakistan",
CountryCode = "PK",
Currency = "Rupee",
Code = "PKR"
};
string fileContent = JsonConvert.SerializeObject(country);
OR
string fileContent = @ "[ {
'Country': 'Nigeria',
'CountryCode': 'NG',
'Currency': 'Naira',
'Code': 'NGN'
}, {
'Country': 'Pakistan',
'CountryCode': 'PK',
'Currency': 'Rupee',
'Code': 'PKR'
}]";
string filePath = System.Web.HttpContext.Current.Server.MapPath("~/Content/File/jsondata.json");
try {
if (System.IO.File.Exists(filePath))
System.IO.File.Delete(filePath);
var W = new StreamWriter(filePath);
W.WriteLine(fileContent);
W.Close();
} catch (Exception e) {
Console.WriteLine(e);
throw;
}