How to access a file server share from an ASP.NET Core web API application published in IIS within the same domain?

1.2k Views Asked by At

I need access to files that are in a files server in my LAN from my Angular app.

I assume that I need to publish my Angular app in the same network, that is, in my IIS Server inside the same LAN

Now on my local machine, I try to access my shared folder \192.168.100.7\OfertasHistoric" but I don´t know how to do it.

When I try this

[HttpGet("directorio")]
public async Task<ActionResult<string[]>> GetDirectoryContents()
{
  string[] files = Directory.GetFiles(@"\\192.168.100.7\ofertashistorico");
  return files;
}

I get this error

System.IO.DirectoryNotFoundException: Could not find a part of the path '/Users/kintela/Repos/Intranet-WebAPI/Intranet.API/\192.168.100.7\ofertashistorico'

It seems that the path that you give to the GetFiles method only searches from the current directory where the project is located downwards and I don't know how to indicate a different one.

I also do not know how to manage the issue of the credentials necessary to access said resource

Any idea, please?

Thanks

1

There are 1 best solutions below

0
Jason Pan On

I am using below code and it works for me. Please check it.

Steps:

  1. Navigate to the path like : \\192.168.2.50\ftp

    enter image description here

  2. Delete \ftp, the address in folder explorer should be \\192.168.2.50, find the folder you want, right click and map network drive.

    enter image description here

    enter image description here

  3. You can try it with this address ftp:\\192.168.2.50, it will pop up a window. Input you usename and password, then you can check the files.

    enter image description here

    enter image description here

Test Result

enter image description here

Sample code

    [HttpGet("directorio")]
    public IActionResult GetDirectoryContents()
    {
        string networkPath = @"ftp:\\192.168.2.50";
        string userName = @"Administrator";
        string password = "Yy16";

        #region FtpWebRequest
        var networkCredential = new NetworkCredential(userName, password);
        var uri = new Uri(networkPath);

        var request = (FtpWebRequest)WebRequest.Create(uri);
        request.Credentials = networkCredential;
        request.Method = WebRequestMethods.Ftp.ListDirectory;
        try
        {
            using (var response = (FtpWebResponse)request.GetResponse())
            {
                using (var stream = response.GetResponseStream())
                {
                    using (var reader = new StreamReader(stream))
                    {
                        Console.WriteLine(reader.ReadToEnd());
                    }
                }
            }
        }
        catch (WebException ex)
        {
            Console.WriteLine("Access to the path '" + networkPath + "' is denied. Error message: " + ex.Message);
        }
        #endregion

        return Ok();
    }