2014-03-28 86 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分钟前发布。 –