我正在使用 ssh.net 将c#对象作为JSON写入SFTP服务器上的文本文件。
我能够写它,但双引号正在从 Json 属性中删除,如何持久化它?
using (var client = new SshClient(sftpServer, sftpUserName, sftpPassword))
{
client.Connect();
if (client.IsConnected)
{
// Check if the Folder Already Exists
var ifExists = client.RunCommand("cat /etc/passwd | grep -w " + directoryName);
if (!string.IsNullOrEmpty(ifExists.Result))
{
var fileExist = client.RunCommand("cat /etc/passwd | find /sftpusers/" + directoryName + "/schema -name " + fileName + ".txt");
if (fileExist != null && string.IsNullOrEmpty(fileExist.Result))
{
client.RunCommand("echo " + sftpPassword + " | sudo -S touch /sftpusers/" + directoryName + "/schema/" + fileName + ".txt");
}
var jsonData = "{"type":"record","name":"asb","namespace":"Employee","Fields":[{"name":"PurchaseId","type":"numeric","ClientFieldNm":null,"ImportFieldLenQty":0,"ImportRetainFlag":false,"ImportPrimaryKeyFlag":0,"ImportResolveFKFieldFlag":0,"ImportDeblankDataFlag":false,"ImportEncryptFlag":false,"ImportBatIndexFlag":false,"ImportEnforceValidTypeFlag":false,"ImportRequiredFlag":false}]}";
var query = string.Format("echo Asdf@123 | sudo -S sh -c 'echo {0} > $1' -- /sftpusers/test/schema/{1}.txt",jsonData, fileName);
client.RunCommand(query);
}
}
client.Disconnect();
}
而不是使用字符串Newtosoft json序列化程序,但也如上述字符串一样工作。
文件名中的当前数据.txt:
{type:record,name:asb,namespace:Employee,Fields:[{name:PurchaseId,type:numeric,ClientFieldNm:null,ImportFieldLenQty:0,ImportRetainFlag:false,ImportPrimaryKeyFlag:0,ImportResolveFKFieldFlag:0,ImportDeblankDataFlag:false,ImportEncryptFlag:false,ImportBatIndexFlag:false,ImportEnforceValidTypeFlag:false,ImportRequiredFlag:false}]}
文件名.txt中的预期数据:
{
"type":"record",
"name":"asb",
"namespace":"Employee",
Fields[{
"name":"PurchaseId",
"type":"numeric",
"ClientFieldNm":null,
"ImportFieldLenQty":0,
"ImportRetainFlag":false,
"ImportPrimaryKeyFlag":0,
"ImportResolveFKFieldFlag":0,
"ImportDeblankDataFlag":false,
"ImportEncryptFlag":false,
"ImportBatIndexFlag":false,
"ImportEnforceValidTypeFlag":false
,"ImportRequiredFlag":false
}]}
你真的不应该为此使用echo
。使用该库上的SftpClient
(而不是SshClient
)将实际文件上载到远程服务器。
但除此之外,您需要转义 shell 命令的引号,因此请尝试如下操作:
jsonData = jsonData.Replace(@"""", @"""");
在呼应之前。
请注意,您执行命令的方式,如果您的jsonData
包含单引号 ('
),您还需要对其进行转义(否则,它会像命令的'echo {0} > $1'
部分的结尾一样看向 shell。