C# save files to folder on server instead of local

后端 未结 1 1155
执念已碎
执念已碎 2020-12-06 13:44

The project is an MVC 4 C# based web application.

I\'m currently working locally and would like to have the ability to upload a file to my locally running applicatio

相关标签:
1条回答
  • 2020-12-06 14:22

    The SaveAs function takes a filename and will save the file to any path you give it, providing the following conditions are met:

    • Your local machine can access the filepath
    • Your local account has the correct privileges to write to the filepath

    I would suggest you have a web.config setting that can be checked when running your code. Then you can decide if to use Server.MapPath or an absolute path instead.

    For example, in "debug" mode (running locally) you might have the following settings:

    <appSettings>
        <add key="RunningLocal" value="true" />
        <add key="ServerFilePath" value="\\\\MyServer\\SomePath\\" />
    </appSettings>
    

    and in "live" mode:

    <appSettings>
        <add key="RunningLocal" value="false" />
        <add key="ServerFilePath" value="NOT USED" />
    </appSettings>
    

    Then your code may look something like this:

    bool runningLocal = GetFromConfig();
    bool serverFilePath = GetFromConfig();
    string filePath;
    
    if(runningLocal)
        filePath = serverFilePath;
    else
        filePath = Server.MapPath(PicturePath);
    
    if (!System.IO.File.Exists(filePath ))
    {
         file.SaveAs(filePath );
    }
    
    0 讨论(0)
提交回复
热议问题