Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

Uploading Files to Network Shared Folders in ASP.NET

Tech May 15 1

Overview

This article demonstrates how to upload files to a network shared folder from an ASP.NET application. The solution uses UNC paths to connect to remote shared directories and transfer files programmatically.

Configuration

Add the following settings to your web.config file under the appSettings section:

<add key="SharedFolderPath" value="\\192.168.1.100\SharedFiles" />
<add key="DownloadBaseUrl" value="http://example.com:8080/" />
<add key="SharedFolderUser" value="FileServiceAccount" />
<add key="SharedFolderPassword" value="SecureP@ss123" />

Configurration Helper

public static class ConfigurationManager
{
    public static string GetSetting(string key, string defaultValue = "")
    {
        return System.Configuration.ConfigurationManager.AppSettings[key] ?? defaultValue;
    }
}

File Type Classification

Different file types are organized into separate folders based on their extensions:

public static class FileTypeResolver
{
    public static string GetTargetDirectory(string fileName)
    {
        if (string.IsNullOrEmpty(fileName))
            return "misc";

        var extension = Path.GetExtension(fileName)?.TrimStart('.').ToLowerInvariant();
        
        return extension switch
        {
            "jpg" or "jpeg" or "png" or "gif" or "bmp" => "images",
            "mp4" or "avi" or "mkv" or "mov" => "videos",
            "apk" or "ipa" => "applications",
            "ppt" or "pptx" or "doc" or "docx" or "xls" or "xlsx" or "pdf" => "documents",
            _ => "misc"
        };
    }
}

Constants

public static class UploadConstants
{
    public static string SharedFolderPath => ConfigurationManager.GetSetting("SharedFolderPath");
    public static string DownloadBaseUrl => ConfigurationManager.GetSetting("DownloadBaseUrl");
    public static string SharedFolderUser => ConfigurationManager.GetSetting("SharedFolderUser");
    public static string SharedFolderPassword => ConfigurationManager.GetSetting("SharedFolderPassword");
}

File Upload Implementation

Upload Controller Endpoint

[HttpPost]
[Route("api/files/upload")]
[AllowAnonymous]
public async Task<FileUploadResult> UploadFile()
{
    var response = new FileUploadResult();
    
    if (HttpContext.Current.Request.Files.Count == 0)
    {
        response.Success = false;
        response.Message = "No file provided";
        return response;
    }

    var uploadedFile = HttpContext.Current.Request.Files[0];
    var originalFileName = Path.GetFileName(uploadedFile.FileName);
    
    var targetFolder = FileTypeResolver.GetTargetDirectory(originalFileName);
    var remoteBasePath = Path.Combine(UploadConstants.SharedFolderPath, targetFolder);
    
    var timestamp = DateTime.Now.ToString("yyyyMMddHHmmss");
    var newFileName = $"{timestamp}_{originalFileName}";
    
    var isConnected = EstablishNetworkConnection(
        UploadConstants.SharedFolderPath,
        UploadConstants.SharedFolderUser,
        UploadConstants.SharedFolderPassword);

    if (!isConnected)
    {
        response.Success = false;
        response.Message = "Failed to connect to network shared folder";
        return response;
    }

    await TransferFileToRemote(uploadedFile.InputStream, remoteBasePath, newFileName);

    response.Success = true;
    response.Message = "File uploaded successfully";
    response.RelativePath = $"{targetFolder}/{newFileName}";
    response.FullDownloadUrl = Path.Combine(UploadConstants.DownloadBaseUrl, response.RelativePath);

    return response;
}

Network Connection Manager

public static class NetworkConnectionHelper
{
    public static bool EstablishNetworkConnection(string uncPath, string username, string password)
    {
        var connectionEstablished = false;
        
        using var process = new System.Diagnostics.Process();
        process.StartInfo.FileName = "cmd.exe";
        process.StartInfo.UseShellExecute = false;
        process.StartInfo.RedirectStandardInput = true;
        process.StartInfo.RedirectStandardOutput = true;
        process.StartInfo.RedirectStandardError = true;
        process.StartInfo.CreateNoWindow = true;
        process.Start();

        var netUseCommand = $"net use {uncPath} {password} /user:{username}";
        process.StandardInput.WriteLine(netUseCommand);
        process.StandardInput.WriteLine("exit");

        process.WaitForExit(5000);
        
        var errorOutput = process.StandardError.ReadToEnd();
        
        if (string.IsNullOrWhiteSpace(errorOutput))
        {
            connectionEstablished = true;
        }
        else
        {
            System.Diagnostics.Debug.WriteLine($"Network connection error: {errorOutput}");
        }

        return connectionEstablished;
    }
}

File Transfer Service

public static class RemoteFileTransfer
{
    public static async Task TransferFileToRemote(Stream sourceStream, string destinationDirectory, string fileName)
    {
        if (!Directory.Exists(destinationDirectory))
        {
            Directory.CreateDirectory(destinationDirectory);
        }

        var destinationPath = Path.Combine(destinationDirectory, fileName);
        
        if (File.Exists(destinationPath))
        {
            return;
        }

        using var outputStream = new FileStream(
            destinationPath, 
            FileMode.Create, 
            FileAccess.Write,
            FileShare.None,
            bufferSize: 4096,
            useAsync: true);

        await sourceStream.CopyToAsync(outputStream);
        await outputStream.FlushAsync();
    }
}

Response Model

public class FileUploadResult
{
    public bool Success { get; set; }
    public string Message { get; set; }
    public string RelativePath { get; set; }
    public string FullDownloadUrl { get; set; }
}

Key Points

  • The shared folder must be accessible with proper network credentials
  • The application pool identity or the configured user must have write permissions to the shared folder
  • Consider implementing connecsion pooling or connection caching for better performance
  • File naming includes timestamp to prevent overwrites
  • Async file operations are recommended for better scalability

Related Articles

Comprehensive Guide to SSTI Explained with Payload Bypass Techniques

Introduction Server-Side Template Injection (SSTI) is a vulnerability in web applications where user input is improper handled within the template engine and executed on the server. This exploit can r...

Implement Image Upload Functionality for Django Integrated TinyMCE Editor

Django’s Admin panel is highly user-friendly, and pairing it with TinyMCE, an effective rich text editor, simplifies content management significantly. Combining the two is particular useful for bloggi...

SBUS Signal Analysis and Communication Implementation Using STM32 with Fus Remote Controller

Overview In a recent project, I utilized the SBUS protocol with the Fus remote controller to control a vehicle's basic operations, including movement, lights, and mode switching. This article is aimed...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.