C# - 当另一个程序正在写入文件时无法将文件上传到 FTP 服务器
C# - Can't upload a file to FTP server while file is being written on by another program
我基本上是在尝试跟踪我 PC 上的特定文件,只要文件内容发生变化,它就应该上传到我的 FTP 服务器。我面临的问题是,当文件当前正在由另一个进程写入时,它不会让我上传到我的 FTP 服务器。我已经尝试了所有方法,包括在管理员中打开等,但此错误(550 权限被拒绝)来自 FTP 服务器。
这是我的代码:
public static void Trace()
{
string checksum = "";
while (true)
{
if (CheckMd5(Path) != checksum)
{
UploadFile1();
}
checksum = CheckMd5(Path);
Thread.Sleep(5000);
}
}
public static void UploadFile1()
{
var ftp1 = new myFTP();
if (!File.Exists(Path))
{
}
else
{
var currentTime = CurrentTime; // gets the current time
ftp1.UploadFile(Path, timeRn);
}
}
public void UploadFile(string filePath, string CurrentTime)
{
FtpWebRequest request =
(FtpWebRequest)WebRequest.Create("ftp://127.0.0.1/" + CurrentTime);
request.Method = WebRequestMethods.Ftp.UploadFile;
request.Credentials = new NetworkCredential("user", "password");
request.UsePassive = true;
request.UseBinary = true;
request.KeepAlive = false;
request.EnableSsl = false;
FileStream stream = File.Open(filePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
byte[] buffer = new byte[stream.Length];
stream.Read(buffer, 0, buffer.Length);
stream.Close();
Stream reqStream = request.GetRequestStream();
reqStream.Write(buffer, 0, buffer.Length);
reqStream.Close();
}
您可能应该重组这 2 个进程,以便文件更改进程在完成文件更改后触发一个事件,而 ftp- 上传进程应该停止通过循环和比较校验和强制进入值(让它处于休眠状态并等待文件完成信号)。这种方法将提高您的应用程序的性能作为奖励(除了您需要的准确性)。
除此之外,也许尝试使用 FileSystemWatcher class。您只能过滤修改事件。
我基本上是在尝试跟踪我 PC 上的特定文件,只要文件内容发生变化,它就应该上传到我的 FTP 服务器。我面临的问题是,当文件当前正在由另一个进程写入时,它不会让我上传到我的 FTP 服务器。我已经尝试了所有方法,包括在管理员中打开等,但此错误(550 权限被拒绝)来自 FTP 服务器。
这是我的代码:
public static void Trace()
{
string checksum = "";
while (true)
{
if (CheckMd5(Path) != checksum)
{
UploadFile1();
}
checksum = CheckMd5(Path);
Thread.Sleep(5000);
}
}
public static void UploadFile1()
{
var ftp1 = new myFTP();
if (!File.Exists(Path))
{
}
else
{
var currentTime = CurrentTime; // gets the current time
ftp1.UploadFile(Path, timeRn);
}
}
public void UploadFile(string filePath, string CurrentTime)
{
FtpWebRequest request =
(FtpWebRequest)WebRequest.Create("ftp://127.0.0.1/" + CurrentTime);
request.Method = WebRequestMethods.Ftp.UploadFile;
request.Credentials = new NetworkCredential("user", "password");
request.UsePassive = true;
request.UseBinary = true;
request.KeepAlive = false;
request.EnableSsl = false;
FileStream stream = File.Open(filePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
byte[] buffer = new byte[stream.Length];
stream.Read(buffer, 0, buffer.Length);
stream.Close();
Stream reqStream = request.GetRequestStream();
reqStream.Write(buffer, 0, buffer.Length);
reqStream.Close();
}
您可能应该重组这 2 个进程,以便文件更改进程在完成文件更改后触发一个事件,而 ftp- 上传进程应该停止通过循环和比较校验和强制进入值(让它处于休眠状态并等待文件完成信号)。这种方法将提高您的应用程序的性能作为奖励(除了您需要的准确性)。
除此之外,也许尝试使用 FileSystemWatcher class。您只能过滤修改事件。