Home > Enterprise >  Upload file to UNC path from Blazor Server app
Upload file to UNC path from Blazor Server app

Time:10-07

I have a Blazor Server app and I followed some Microsoft example code to upload files to a local path on my C drive which works fine:

   string path = Path.Combine(_environment.ContentRootPath, "MediaFiles", file.Name);
   await using FileStream fs = new(path, FileMode.Create);
   await file.OpenReadStream(maxFileSize).CopyToAsync(fs);

This will eventually go to other environments for testing and the production. For that, we have shared directories on the servers. In my test, I changed the path to a UNC path:

var root = "\\SomeRemoteServer";
var folder = "destinationFolder";

string path =  string path = Path.Combine(root, folder, file.Name);
await using FileStream fs = new(path, FileMode.Create); //This line throws the error
await file.OpenReadStream(maxFileSize).CopyToAsync(fs);

The line marked above throws this error:

System.IO.DirectoryNotFoundException: 'Could not find a part of the path 'C:\<remoteServerName>\<foldername>\<fileName>'.'

I don't know why it is putting a "C:\" in front of the path. Is there any way to avoid this? Am I just going about this the wrong way for a UNC path? I run this using F5, do I need to set it up to run in IIS as an application and have a virtual directory? Just to note that the directory exists and can be accessed from my local machine with a UNC path. There is no access/permissions error

Thank you for any guidance.

CodePudding user response:

Since you are using:

var root = "\\SomeRemoteServer";
var folder = "destinationFolder";
string path = Path.Combine(root, folder, file.Name); 

The value of path will actually be "\SomeRemoteServer\destinationFolder\?". Note that the "\" actually causes the slash to be escaped, not doubled as it should be in a UNC path. It appears that the FileStream object will then interpret "\SomeRemoteServer\destinationFolder\?" as "C:\SomeRemoteServer\destinationFolder\?" because it is using a local absolute path reference and the web app is running on the C: drive. You have a couple options.

Option 1 - use a string verbatim identifier when defining your root:

var root = @"\\SomeRemoteServer";

Option 2 - escape both of the UNC slashes:

var root = "\\\\SomeRemoteServer";
  • Related