我有此PHP代码,它将接受CSV文件并将其移至服务器上的目录。我正在努力使用C#控制台应用程序.NET 4.7.2 Framework做完全相同的事情]
我看过一些有关C#Web编程的视频,但对以下方法感到困惑套接字,侦听器和TCP / IP。如果有人可以翻译代码,我将不胜感激下面是C#的代码,因此我至少将有一个可行的示例来开始实验和学习。
谢谢!
$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');
}
}
C#控制台应用程序是客户端应用程序。您的控制台应用程序只能由直接使用安装的PC的人与之交互。 PHP是一种服务器端语言,可以通过HTTP协议通过Internet进行访问。
我们无法在此处为您编写应用,但是,我可以为您指明正确的方向。问问自己:为什么要使用C#控制台应用程序?我需要这个程序在互联网上工作还是在本地/离线工作是否正常?
如果标题正确,并且您想使用HTTP Post,则需要制作一个服务器端C#应用程序-而不是控制台应用程序(它将无法运行)。我建议您研究一下ASP.net Core MVC,您可以说这是基于C#的服务器端应用程序的“默认”选择。