“Could not find a part of the path” Error For File Read Operation in Azure WebApp

老子叫甜甜 提交于 2019-12-10 12:15:40

问题


I have MVC application which is having browse button I'm selecting file any location and reading file content using path and then process the content.

Works fine in local but when published on azure as web app obvious it was not able to get the file system path but how to handle this?

Could not find file 'D:\Windows\system32\mydata.json'.

Index.cshtml

 <label>File Path</label>
    <table>
      <tr>
        <td>@Html.TextBoxFor(m => m.filePath, new { type = "file", @class = "input-file" }) )</td>
        <td>&nbsp;&nbsp;</td>

      </tr>
    </table>

HomeController.cs

private static void Test(string filepath)
        {
            string data = System.IO.File.ReadAllText(filepath);
            JArray array = JArray.Parse(data);

回答1:


On Azure the process current working directory is D:\Windows\system32\, try var wholePath = Path.Combine(Server.MapPath("~/"), filepath); to locate files under web root.

Update

Add HttpPostedFileBase field to your Model. In your View, change to m => m.File.

public class FileModel 

{
    public HttpPostedFileBase File { get; set; }
}

In Controller

public ActionResult FileUpload(FileModel fileModel)
{
    if (ModelState.IsValid)
    {
         StreamReader s = new StreamReader(fileModel.File.InputStream);
         JArray array = JArray.Parse(s.ReadToEnd());
         ...
     }
     return View();
}



回答2:


You're trying to read a file that is on a client machine in code that's executing on the server. That won't work. Your server doesn't have access to files in the client machine. Which is a good thing 😁

Have a look at HttpPostedFileBase to upload files.



来源:https://stackoverflow.com/questions/53108415/could-not-find-a-part-of-the-path-error-for-file-read-operation-in-azure-webap

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!