2014-03-28 90 views
0

我正確的做了什麼,sourcepath是文檔的文件路徑。 1)測試文件是否存在,如果它沒有拋出異常 2)現在我們知道文件存在(並且因爲文件正在從其他地方下載)檢查它是否包含數據。 (因爲它不應該是空的),如果它是空的拋出錯誤,....將檢查這個文件是否爲空的工作?我可以檢查下載的文件是否包含數據?

string sourcePath = "C:\Users\Martin\Desktop\document5.docx"; 

if (!File.Exists(sourcePath)) 
{ 
//throw exception 
} 

if (string.IsNullOrEmpty(sourcePath)) 
{ 
//throw exception 
} 
+0

什麼是下載它的代碼? *那*應該知道,當然?另外:你提到mvc,它建議服務器端,但你提到訪問下載文件,這表明客戶端。您的網絡服務器是否將文件從其他地方下載到網絡服務器的文件系統?要麼...?如果下載的文件來自*您的網絡服務器,則立即停止:您的服務器無法告知任何有關瀏覽器文件系統的信息。 –

+0

它是一個來自本頁下載()的ftp http://www.codeproject.com/Tips/443588/Simple-Csharp-FTP-Class – John

回答

4

您的代碼只會檢查(a)文件是否存在於磁盤上(不必有任何數據)或(b)路徑中有內容。

爲了準確地測試,如果文件中有數據,你可以使用:

var file = new FileInfo(sourcePath); 
if (file.Length == 0) 
{ 
//throw exception 
} 

更多的信息在這裏...

http://msdn.microsoft.com/en-us/library/system.io.fileinfo.length(v=vs.110).aspx


順便說一句,路徑你」已在第一行宣佈無效。你需要轉義字符串爲它被視爲一個有效的路徑,所以更改:

string sourcePath = "C:\Users\Martin\Desktop\document5.docx"; 

這樣:

string sourcePath = @"C:\Users\Martin\Desktop\document5.docx"; 
0

鑑於你在哪裏的數據是從哪裏來的評論;只是編輯代碼

// taken from example linked in comment 
public long download(string remoteFile, string localFile) 
{ 
    long totalBytes = 0; 
    try 
    { 
     // ...blah 
     try 
     { 
      while (bytesRead > 0) 
      { 
       localFileStream.Write(byteBuffer, 0, bytesRead); 
       totalBytes += bytesRead; 
       bytesRead = ftpStream.Read(byteBuffer, 0, bufferSize); 
      } 
     } 
     // ...blah 
    } 
    catch (Exception ex) { Console.WriteLine(ex.ToString()); } 
    return totalBytes; 
} 

,只是檢查是否返回零或非零。此外,這是非常可怕的異常處理(在這裏我用「處理」相當不正確)。

0

你可以通過它的檢查length

FileInfo fileInfo = new FileInfo(sourcePath); 

if (fileInfo.Length > 0) 
{ 
    // file has content. file downloaded. 
} 
else 
{ 
    //throw exception 
} 
+2

確切的答案已經在10分鐘前發佈。 –