6

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 application in debug mode and have the file saved to the web server instead of the my local folder.

Currently we are using:

if (!System.IO.File.Exists(Server.MapPath(PicturePath)))
{
     file.SaveAs(Server.MapPath(PicturePath));
}

How can we leverage this code to save to a webserver directly. Is that even possible?

Right now the file gets saved to my local path and the path is stored in the database, we then have to upload the files to the webserver manually.

Rob Carroll
  • 377
  • 1
  • 7
  • 16
  • Why don't you deploy your app to the web server? – Icarus Jul 24 '13 at 15:50
  • Just to be clear, you want to run your app locally, but save the image to your webserver? Why dont you just save the images to a shared folder on your webserver? – chris.ellis Jul 24 '13 at 15:57
  • Because I'm debugging on my local environment and getting all the bugs worked out before deploying the application. – Rob Carroll Jul 24 '13 at 15:57

1 Answers1

8

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 );
}
musefan
  • 47,875
  • 21
  • 135
  • 185
  • So if I use the direct filepath from my local to the webserver I should be able to save it directly to that location as long as my account on my local has write access to that directory? – Rob Carroll Jul 24 '13 at 15:56
  • @RobCarroll: Correct. Just keep in mind, if you are running locally using IIS, it will be the user account used within IIS that needs to have access – musefan Jul 24 '13 at 15:58
  • what GetFromConfig() do it not working for me should i include a namespace or anything else – Fadi Jul 15 '14 at 18:50
  • @Fadi: `GetFromConfig()` is just a made up function to indicate that you should get the paths from your config files (or wherever else you want to store them) – musefan Jul 16 '14 at 08:02