ASP.NET MVC Website Read File from Disk Problem

后端 未结 3 1880
眼角桃花
眼角桃花 2021-01-06 06:31

I\'m reading a text file containing an insert statement for SQL using C# in an MVC Website I\'m working on. When debugging the function I\'m using works fine and the insert

相关标签:
3条回答
  • 2021-01-06 06:56

    Workaround:

    Instead of using

    Server.MapPath("\\temp\\"...
    

    Create folder under root with name "temp" and use

    System.Web.HttpContext.Current.Request.MapPath("~\\temp....
    
    0 讨论(0)
  • 2021-01-06 06:57

    Well, "it doesn't seem to work" is pretty vague - a bit more detail would be nice! But it sounds like a permissions issue. The default profile in IIS has very little access to the disk, especially write access. It isn't really a good idea to write inside your own site anyway (I'd use an unrelated part of the disk, myself), but you will need to configure IIS to run the application in a specific named identity, with access to the disk. Configuring the account itself (not IIS - the account; for example granting "logon as a service") to run as an ASP.NET account is not particularly trivial, unfortunately.

    Another thought: is your app a sub-application, i.e. is your app-root /, or is it /MyApp/ ? The reason I ask is your use of MapPath might be better expressed relative to the app-root, i.e. ~/temp/ - but again I stress; writing inside the app is risky. You really want that folder to be non-executing.

    0 讨论(0)
  • 2021-01-06 07:10

    There may be an alternative solution to this problem. You can avoid messing with path and file system altogether if you can 'bake' the file into assembly at build time. Here is how you can do this:

    1. In Visual Studio solution explorer right click on a file and go to Properties.

    2. Set Build Action to 'Embedded Resource'.

    3. Later you can read the file using GetManifestResourceStream:

          var stream = GetType()
              .Assembly
              .GetManifestResourceStream("YourNameSpace.Folder.YourFile.txt");
      
          using (var reader = new StreamReader(stream)) {
              var fileContent = reader.ReadToEnd();
          }
      

      More info here.

    0 讨论(0)
提交回复
热议问题