【问题标题】:Check Empty System.IO.FileStream is empty检查 Empty System.IO.FileStream 是否为空
【发布时间】:2017-12-07 02:57:28
【问题描述】:

我要做的是在用户单击按钮而不将图像上传到 FileStream 时返回一个消息框。

 FileStream stream = new FileStream(imgLocation, FileMode.Open, FileAccess.Read);
        BinaryReader brs = new BinaryReader(stream);
        images = brs.ReadBytes((int)stream.Length);

        SqlCommand cmd = new SqlCommand(sql, con);
        cmd.Parameters.Add(new SqlParameter("@images", images));


        MessageBox.Show("Upload complete");
        cmd.ExecuteNonQuery();
        con.Close();

程序显示“空路径名不合法”错误。如何检查空路径名并返回消息框?

【问题讨论】:

  • 您的错误到底是什么(即,它是编译错误,运行时异常,如果异常是实际异常,还是其他什么?),在哪一行?如果它在您从路径生成文件流的第一行,它不像检查您的 imgLocation 不为空那么容易吗?
  • 刚刚检查了 imgLocation 的传递 "" 将生成带有消息“空路径名不合法”的 ArgumentException。那么你到底在哪里遇到了麻烦?该消息似乎很清楚您的问题是什么。你不知道如何检查一个字符串是否为空?这个条件逻辑还有其他问题吗?
  • if (String.IsNullOrEmpty(imgLocation)) MessageBox.Show("Empty path");

标签: c# winforms memorystream


【解决方案1】:

您可以在此处进行多项检查:

  1. 检查字符串是否为空:

    if (string.IsNullOrEmpty(imgLocation)) MessageBox.Show("Invalid path");
    
  2. 检查后您可以在 FileInfo 类中加载位置:

    FileInfo file = new FileInfo(path);
    

然后检查多项:

   if(file.Exists) //Check file's existence
   if(file.Length == 0) //Check if file is not empty

在对文件进行操作之前。

你也可以检查:(如果你想跳过file.Length)

    FileStream stream = new FileStream(imgLocation, FileMode.Open, FileAccess.Read);
    if(stream.Length==0) //check if stream is empty

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-05-27
    • 1970-01-01
    • 2010-12-23
    • 2013-07-18
    • 2013-07-12
    • 2013-07-27
    • 2015-08-09
    • 2017-06-14
    相关资源
    最近更新 更多