【发布时间】:2019-08-13 00:34:15
【问题描述】:
我正在创建一个带有多个文本框的 C# Windows 窗体应用程序,其中我将用户输入保存为 JSON。 在反序列化之后,我正在从这样的 JSON 文件中检索用户输入:
string host2 = currentList[1].IPaddress;
string username2 = currentList[1].username;
string password2 = currentList[1].password;
string remoteDirectory2 = currentList[1].sourcefolder;
string localDirectory2 = currentList[1].destfolder;
string filextension2 = currentList[1].filextension;
string removedownloaded2 = currentList[1].removedownloaded.ToString();
这是我的 json 字符串结构。
{
"Record": 2,
"IPaddress": "192.168.6.247",
"Machinename": "taurus",
"username": "root",
"password": "root",
"sourcefolder": "/home/root/bin",
"destfolder": "D:/DataProfiler_Nautitech/Files",
"filextension": ".sh",
"removedownloaded": 1
}
目标如下:
连接到 SFTP 服务器。
将文件下载到本地服务器。
如果 removedownloaded == 1,则删除这些文件。
如果 removedownloaded == 0,则保留这些文件。
我试过下面的方法
if (removedownloaded2 == "1")
{
//First method
sftp2.Delete(path);
//Second method
sftp2.DeleteDirectory(path);
//Third method
sftp2.DeleteFile(path);
}
但这些都没有删除任何文件。
这是完整的代码:(失败!)
using (SftpClient sftp2 = new SftpClient(host2, username2, password2))
{
try
{
sftp2.Connect();
Console.WriteLine("Machine 2 - Connected");
var files = sftp2.ListDirectory(remoteDirectory2);
foreach (var file in files)
{
try
{
string remoteFileName = file.Name;
if ((file.Name.EndsWith(filextension2)))
{
using (Stream file1 = File.OpenWrite(Path.Combine(localDirectory2, remoteFileName)))
{
string path = remoteDirectory2 + "/" + remoteFileName;
sftp2.DownloadFile(path, file1);
if (removedownloaded2 == "1")
{
//First method
sftp2.Delete(path);
//Second method
//sftp2.DeleteDirectory(path);
//Third method
//sftp2.DeleteFile(path);
}
}
}
}
catch (Exception er1)
{
//MessageBox.Show("An exception has been caught " + er1.ToString());
}
}
}
catch (Exception entry)
{
MessageBox.Show(entry.Message);
}
//finally
//{
// sftp2.Disconnect();
//}
}
下载后如何删除文件有什么想法吗?提前感谢您的帮助。
【问题讨论】:
-
你有什么异常吗?如果您在 foreach 循环中取消注释
catch block中的代码,您会收到任何消息框吗?我建议调试你的代码。 -
你有解决这个问题的方法吗?
-
从那以后我就没有工作过,我还没有答案