编辑文本文件驻留在网络(局域网)
本文关键字:网络 局域网 文本 文件 编辑 | 更新日期: 2023-09-27 18:04:45
我想访问和编辑文本文件从c#应用程序是在网络上,并通过ip地址访问。访问文件不需要凭据,所以我想要一些示例代码或指南,如何开始实现此任务。我想编辑的文件是在安卓平板电脑和Android应用程序(SD卡)的存储,我通过ip地址访问,因为我的机器和安卓设备在同一网络上。由于
try
{
StreamReader sr = new StreamReader("192.168.1.2/NewFolder/TickerText.txt");
//Read the first line of text
line = sr.ReadLine();
//Continue to read until you reach end of file
while (line != null)
{
//write the lie to console window
textBox1.Text=line;
//Read the next line
line = sr.ReadLine();
}
//close the file
sr.Close();
Console.ReadLine();
}
catch(Exception ae)
{
textBox1.Text = ae.Message;
}
假设两台计算机都是windows,您可以共享文件所在的文件夹,并使用以下命令访问该文件夹:
using (StreamWriter writer = new StreamWriter(@"''IPADDRESS'directories'file.txt")
{
writer.Write("Word ");
}
和阅读:
File.ReadAllLines(@"''IPADDRESS'directories'file.txt");
与其他文件读取/写入器相同。
由于文件所在的android操作系统的附加信息,以及FTP的包含,我只能说
- simple-ftp-get-file
- net-ftpwebrequest
- FtpWebRequest <—defiant c# ftp项目
将对你有用。
我将粘贴来自CodeProject文章的相关信息。这些代码都不是我的,但是它会做你需要的。
只要记得在你完成后将文件上传到android系统。
/* Download File */
public void download(string remoteFile, string localFile)
{
try
{
/* Create an FTP Request */
ftpRequest = (FtpWebRequest)FtpWebRequest.Create(host + "/" + remoteFile);
/* Log in to the FTP Server with the User Name and Password Provided */
ftpRequest.Credentials = new NetworkCredential(user, pass);
/* When in doubt, use these options */
ftpRequest.UseBinary = true;
ftpRequest.UsePassive = true;
ftpRequest.KeepAlive = true;
/* Specify the Type of FTP Request */
ftpRequest.Method = WebRequestMethods.Ftp.DownloadFile;
/* Establish Return Communication with the FTP Server */
ftpResponse = (FtpWebResponse)ftpRequest.GetResponse();
/* Get the FTP Server's Response Stream */
ftpStream = ftpResponse.GetResponseStream();
/* Open a File Stream to Write the Downloaded File */
FileStream localFileStream = new FileStream(localFile, FileMode.Create);
/* Buffer for the Downloaded Data */
byte[] byteBuffer = new byte[bufferSize];
int bytesRead = ftpStream.Read(byteBuffer, 0, bufferSize);
/* Download the File by Writing the Buffered Data Until the Transfer is Complete */
try
{
while (bytesRead > 0)
{
localFileStream.Write(byteBuffer, 0, bytesRead);
bytesRead = ftpStream.Read(byteBuffer, 0, bufferSize);
}
}
catch (Exception ex) { Console.WriteLine(ex.ToString()); }
/* Resource Cleanup */
localFileStream.Close();
ftpStream.Close();
ftpResponse.Close();
ftpRequest = null;
}
catch (Exception ex) { Console.WriteLine(ex.ToString()); }
return;
}
你可以这样读一个文件:
File.ReadAllLines(@"''192.168.1.1'FileName.txt");
会返回一个string[]
,或者像这样:
foreach (string line in File.ReadLines(@"''192.168.1.1'FileName.txt"))
{
...
}
一行接一行。您可以像这样添加到文件(例如,添加新行):
File.AppendAllText(@"''192.168.1.1'FileName.txt", "Hello, World!");
还有很多其他的方法。利用System.Io
命名空间