我想从网络上的c#应用程序访问和编辑文本文件,并通过ip地址访问。没有访问文件所需的凭据,所以我想要一些示例代码或指导我如何开始实现此任务。我要编辑的文件是在Android平板电脑和Android应用程序(SD卡)的存储我通过IP地址访问,因为我的机器和Android设备在同一网络上。 感谢
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;
}
答案 0 :(得分:3)
假设两台计算机都是Windows,您可以共享该文件所在的文件夹并使用以下方式访问该文件夹:
using (StreamWriter writer = new StreamWriter(@"\\IPADDRESS\directories\file.txt")
{
writer.Write("Word ");
}
并使用以下方式阅读:
File.ReadAllLines(@"\\IPADDRESS\directories\file.txt");
与任何其他文件读取器/写入器相同。
随着涉及android操作系统的附加信息文件打开,并且包含FTP我只能说
对您有用。
我会粘贴CodeProject article的相关信息 这些代码都不是我的,但它会做你需要的 只需记住在完成后将文件上传回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;
}
答案 1 :(得分:1)
您可以阅读如下文件:
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
命名空间。