ASP.NET MVC Website Read File from Disk Problem

后端 未结 3 1918
眼角桃花
眼角桃花 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 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.

提交回复
热议问题