【发布时间】:2016-03-20 12:37:40
【问题描述】:
我正在尝试将数据 (JSON) 从 C# (winforms) 应用程序传递到静态 html/javascript 文件,该文件执行一些画布绘图以根据 JSON 对象中的详细信息呈现图形。 html/javascript 文件仅在浏览器中运行,不需要网络服务器。如果可能的话,我想避免托管 html 文件。
由于不涉及服务器,我假设不可能通过“get”或“post”传递数据?
我尝试将 JSON 写入用户电脑上的文件,从 C# 应用程序(在 javascript 文件上)运行 Process.Start() 以使其在浏览器中打开,然后让页面读取 JSON文件中的数据。这会导致“权限被拒绝错误”。
另外,我发现了以下评论: “HTML5 fileReader 工具确实允许您处理本地文件,但这些必须由用户选择,您不能在用户磁盘上查找文件。” 从这里:How to open a local disk file with Javascript?
如何在没有任何用户干预的情况下将数据从我的应用程序获取到 javascript 文件?还有其他选择吗?
提前感谢您的任何想法/帮助。
C# > 序列化 JSON、写入文件、启动 Javascript 文件...
...
string json = JsonConvert.SerializeObject(this);
sendJson(json);
}
private void sendJson(string json)
{
Assembly assy = Assembly.GetExecutingAssembly();
string appRoot = Path.GetDirectoryName(assy.Location);
string pathToCurveFile = string.Format("{0}\\{1}", appRoot, "WebPages\\curve.htm");
string pathToJsonData = string.Format("{0}\\{1}", appRoot, "WebPages\\curveData.json");
File.WriteAllText(pathToJsonData, json);
}
Javascript > 页面加载时尝试读取 JSON 文件
function init() {
var json;
var dataFilePath = 'file://C:/Temp/curveData.json';
var reader = new FileReader();
reader.onload = function (e) { payload = reader.result; }
reader.readAsText(dataFilePath);
json = JSON.parse(payload);
【问题讨论】:
-
你可以尝试使用.net浏览器控件并在其中加载网页,在
#之后传递数据,然后通过window.location.hash在js中获取。 -
你是如何打开 html 的?来自winform的浏览器控件?如果是这样,您可以在该 html 中添加一个 JS 事件并从 C# 调用它。如果你需要,我可以给你一个例子。您也可以使用参数加载页面。
-
来自 C# 我正在使用 Process.Start(somefile.htm)。我远离浏览器控件的原因是因为我使用的是 HTML5 画布,我认为浏览器控件不会支持它,但可能需要进一步研究。
-
正确,它将使用主机操作系统的IE引擎。请检查以下链接以使其与查询字符串一起使用。
Process.Start("iexplore.exe", @"file:///D:/index.html?name=bob")stackoverflow.com/questions/13550837/… -
您还可以查看使用CefSharp 在您的应用中嵌入铬。
标签: javascript c# jquery json html