我想基本上使用以下代码编辑C#文件:
var file = new StreamReader("ftp://xxx.xxx.x.x/xxx.txt"); //[ip address/file]
label1.Text = file.ReadLine();
file.Close();
var fw = new StreamWriter("ftp://xxx.xxx.x.x/xxx.txt"); //[ip address/file]
fw.WriteLine(textBox1.Text);
fw.Close();
但它不起作用,我该怎么做?
答案 0 :(得分:5)
通过FTP编辑文件:
对于步骤1和3,请检查this。
答案 1 :(得分:2)
与ftplib库相比,FtpWebRequest看起来非常复杂@ http://ftplib.codeplex.com/
这是他们的例子......
using (FtpConnection ftp = new FtpConnection("ftpserver", "username", "password"))
{
ftp.Open(); /* Open the FTP connection */
ftp.Login(); /* Login using previously provided credentials */
if (ftp.DirectoryExists("/incoming")) /* check that a directory exists */
ftp.SetCurrentDirectory("/incoming"); /* change current directory */
if (ftp.FileExists("/incoming/file.txt")) /* check that a file exists */
ftp.GetFile("/incoming/file.txt", false); /* download /incoming/file.txt as file.txt to current executing directory, overwrite if it exists */
//do some processing
try
{
ftp.SetCurrentDirectory("/outgoing");
ftp.PutFile(@"c:\localfile.txt", "file.txt"); /* upload c:\localfile.txt to the current ftp directory as file.txt */
}
catch (FtpException e)
{
Console.WriteLine(String.Format("FTP Error: {0} {1}", e.ErrorCode, e.Message));
}
foreach(var dir in ftp.GetDirectories("/incoming/processed"))
{
Console.WriteLine(dir.Name);
Console.WriteLine(dir.CreationTime);
foreach (var file in dir.GetFiles())
{
Console.WriteLine(file.Name);
Console.WriteLine(file.LastAccessTime);
}
答案 2 :(得分:1)
查看.NET 4.0中包含的FtpWebRequest类以帮助解决此问题。
答案 3 :(得分:0)
我觉得我有点晚了,但是我遇到了和你一样的问题,在我寻找解决方案后,我找到了一种方法来进行更改而无需下载和上传文件。
我的目标是在结束时保存程序执行期间所做的所有更改,并在程序启动时从存储在FTP服务器中的.txt文件加载这些数据。
以下是使用的两种方法:
public static void Save(ArrayList dataStore)
{
WebClient request = new WebClient();
string url = "ftp://ftpname/directory/" + "file.txt";
request.Credentials = new NetworkCredential("username", "password");
Stream postStream = request.OpenWrite(url);
foreach (Data data in dataStore)
{
byte[] writeData = Encoding.ASCII.GetBytes(data + "#");
postStream.Write(writeData, 0, writeData.Length);
}
}
public static ArrayList Load()
{
ArrayList dataStore = new ArrayList();
WebClient request = new WebClient();
string url = "ftp://ftpname/directory/" + "file.txt";
request.Credentials = new NetworkCredential("username", "password");
byte[] newFileData = request.DownloadData(url);
string fileString = Encoding.UTF8.GetString(newFileData);
if (fileString == "")
{
return dataStore;
}
string[] dataString = fileString.Split('#');
foreach (string data in dataString)
{
if (data != "")
{
dataStore.Add(data);
}
}
return dataStore;
}