2013-06-26 45 views
-1

我在Microsoft Visual C#2010 Express中編程。 我的Web服務器上的文件夾中有一個文本文件,其中包含一個字符:'0'。 當我啓動我的C#應用​​程序時,我想從我的文本文件中讀取數字,將其增加1,然後保存新的數字。寫入網絡文本文件

我瀏覽過網頁,但找不到合適的答案。我所得到的是有關從本地文本文件寫入/讀取的問題和答案。

所以基本上,我想寫一些文字到一個文本文件,該文件是不是我的電腦,但這裏: http://mywebsite.xxx/something/something/myfile.txt

這可能嗎?

+1

這是通過ASP.Net嗎? –

+0

或者您是否有桌面應用程序,並且您正嘗試將文本文件寫入另一臺服務器上的目錄? –

+0

誰投了OP? –

回答

0

我發現了一個有效的解決方案,使用文件傳輸協議如巴塔陶提及。然而,我從邁克爾託德那裏瞭解到這是不安全的,所以我不會在自己的應用程序中使用它,但也許這可能對其他人有所幫助。

我發現如何上傳使用FTP文件在這裏的信息:http://msdn.microsoft.com/en-us/library/ms229715.aspx

void CheckNumberOfUses() 
    { 
     // Get the objects used to communicate with the server. 
     FtpWebRequest ftpRequest = (FtpWebRequest)WebRequest.Create("ftp://mywebsite.xx/public_html/something1/something2/myfile.txt"); 
     HttpWebRequest httpRequest = (HttpWebRequest)WebRequest.Create("http://mywebsite.xx/something1/something2/myfile.txt"); 

     StringBuilder sb = new StringBuilder(); 
     byte[] buf = new byte[8192]; 
     HttpWebResponse response = (HttpWebResponse)httpRequest.GetResponse(); 
     Stream resStream = response.GetResponseStream(); 
     string tempString = null; 
     int count = resStream.Read(buf, 0, buf.Length); 
     if (count != 0) 
     { 
      tempString = Encoding.ASCII.GetString(buf, 0, count); 
      int numberOfUses = int.Parse(tempString) + 1; 
      sb.Append(numberOfUses); 
     } 

     ftpRequest.Method = WebRequestMethods.Ftp.UploadFile; 

     // This example assumes the FTP site uses anonymous logon. 
     ftpRequest.Credentials = new NetworkCredential("login", "password"); 

     // Copy the contents of the file to the request stream. 
     byte[] fileContents = Encoding.UTF8.GetBytes(sb.ToString()); 
     ftpRequest.ContentLength = fileContents.Length; 
     Stream requestStream = ftpRequest.GetRequestStream(); 
     requestStream.Write(fileContents, 0, fileContents.Length); 
     requestStream.Close(); 
     FtpWebResponse ftpResponse = (FtpWebResponse)ftpRequest.GetResponse(); 
     ftpResponse.Close(); 
    }  

讀入的問題的意見如何能不使用FTP做得更好。我的解決方案是而不是建議如果您的服務器上有重要文件。

3

您可能需要調整路徑目錄,但這個工程:

string path = Path.GetDirectoryName(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile) + "\\something\\myfile.txt"; 
    string previousNumber = System.IO.File.ReadAllText(path); 
    int newNumber; 
    if (int.TryParse(previousNumber, out newNumber)) 
    { 
     newNumber++; 
     using (FileStream fs = File.Create(path, 1024)) 
     { 
      Byte[] info = new UTF8Encoding(true).GetBytes(newNumber.ToString()); 
      fs.Write(info, 0, info.Length); 
     } 
    } 
+0

+1使用IDisposable對象 –