Search code examples
c#phphttphttpshttp-get

Getting a CSV file via HTTP POST action in C#


I have this PHP code that will accept a CSV file and move it to a directory on the server. I'm straggling to do the exact same thing using C# console application .NET 4.7.2 Framework

I had seen some videos about C# web programming but got confused between the methods of sockets ,listners and TCP/IP . I would very appreciate if someone could translate the code below to C# so I will at least have a working example to start experimenting and learning.

THANKS!

$target_dir = __dir__ . '/uploads';
$default_datasource = 'unknown';
$accepted_mimes = ['text/csv'];

####################

// Make sure the request has expected fields.
if (isset($_POST['action']) && $_POST['action'] === 'upload') {
    $file_path = $target_dir . '/' . ($_POST['datasource'] ?? $default_datasource) . '/' . $_FILES['file']['name'];
    $file_dir  = dirname($file_path);
    $file_mime = $_FILES['file']['type'];
    $file_name = $_FILES['file']['name'];

    if (!in_array($file_mime, $accepted_mimes, true)) {
        $accepted_mimes = implode(',', $accepted_mimes);
        throw new RuntimeException("Invalid file type: '{$file_mime}'. Only {$accepted_mimes} is acceptable");
    }

    if (file_exists($file_path)) {
        throw new RuntimeException('File already exists');
    }

    if (!is_dir($file_dir)) {
        if (!mkdir($file_dir) && !is_dir($file_dir)) {
            throw new RuntimeException(sprintf('Directory "%s" was not created', $file_dir));
        }
    }


    if (move_uploaded_file($_FILES['file']['tmp_name'], $file_path)) {
        echo 'OK';

    } else {
        throw new RuntimeException('Failed to upload file');
    }


}

Solution

  • C# console applications are clientside apps. Your console app will only be interacted with by someone directly using the installed PC. PHP is a serverside language and can be reached across the internet via HTTP protocol.

    We cannot write your app for you here on SO, but, I can point you in the right direction. Ask yourself: Why do you want to use a C# console app? Do I need this app to work over the internet or is it fine for it to work locally/offline?

    If your title is correct, and you want to use HTTP Post, you will need to make a serverside C# application -- NOT a console app (which won't work). I would reccomend you look into ASP.net Core MVC, which you could say is the "default" choice for C# based serverside applications.


    Here is some example code I found on MSDN for a asp.net CORE C# app:

    1) Create a Razor Pages Sample App

    2) Create a new razer page Pages/BufferedSingleFileUploadPhysical.cshtml

    3) Add in the following code

    BufferedSingleFileUploadPhysical.CSHTML (Razer Page)

    <form enctype="multipart/form-data" method="post">
    <dl>
        <dt>
            <label asp-for="FileUpload.FormFile"></label>
        </dt>
        <dd>
            <input asp-for="FileUpload.FormFile" type="file">
            <span asp-validation-for="FileUpload.FormFile"></span>
        </dd>
    </dl>
    <input asp-page-handler="Upload" class="btn" type="submit" value="Upload" />
    

    Source: https://learn.microsoft.com/en-us/aspnet/core/mvc/models/file-uploads?view=aspnetcore-3.1