持续监视文件夹以将新创建 的文件从该文件夹上载到C#中的REST API

问题描述 投票:0回答:1

我一直在搜索和阅读有关内容,但找不到真正有用的东西。

我正在编写一个小型的C#win应用程序,它使我可以通过POST通过HTTP将文件发送到Web服务器,而不是通过FTP,而是通过HTTP。可以将其视为Web表单,但可以在Windows应用程序上运行,并持续监视文件夹中是否有新文件,因此可以将其推送到REST API。

如果您能帮助我,我会很高兴。

我已经输入了密码。

using (WebClient client = new WebClient())
{
    client.Headers.Add("Content-Type", "application/octet-stream");
    using (Stream fileStream = File.OpenRead(filePath))
    using (Stream requestStream = client.OpenWrite(new Uri(fileUploadUrl), "POST"))
    {
        fileStream.CopyTo(requestStream);
    }
}

谢谢!

c# rest api file upload
1个回答
0
投票
虽然不是那么简单。您需要考虑在极端情况下会发生什么(而且很多)。首先,在创建目录然后在其中创建文件时会发生什么,该文件称为1.txt,该文件已存在于父文件夹中。

-1.txt

-NewFolder

--- 1.txt

using (FileSystemWatcher watcher = new FileSystemWatcher()) { watcher.Path = args[1]; // Watch for changes in LastAccess and LastWrite times, and // the renaming of files or directories. watcher.NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite | NotifyFilters.FileName | NotifyFilters.DirectoryName; // Watch every file watcher.Filter = "*"; // Add event handlers. watcher.Created += OnCreated; // Begin watching. watcher.EnableRaisingEvents = true; // Wait for the user to quit the program. Console.WriteLine("Press 'q' to quit the sample."); while (Console.Read() != 'q') ; } // Define the event handlers. private static void OnChanged(object source, FileSystemEventArgs e) { // Specify what is done when a file is changed, created, or deleted. Console.WriteLine($"File: {e.FullPath} {e.ChangeType}"); using (WebClient client = new WebClient()) { client.Headers.Add("Content-Type", "application/octet-stream"); using (Strea mfileStream = File.OpenRead(e.FullPath)) using (Stream requestStream = client.OpenWrite(new Uri(fileUploadUrl), "POST")) { fileStream.CopyTo(requestStream); } } }

© www.soinside.com 2019 - 2024. All rights reserved.