【问题标题】:USING FileStream and handling its weird exceptions使用 FileStream 并处理其奇怪的异常
【发布时间】:2014-12-27 06:22:24
【问题描述】:

当我在我的代码中声明了一个固定的文件+文件路径并且被理解为可以工作时,以下代码适用于我。

  NetworkStream netStream = client.GetStream();
        string FileName = @"D:\John\FYL\video1.mp4";
        Directory.CreateDirectory(Path.GetDirectoryName(FileName));

        using (FileStream fs = new FileStream(FileName, FileMode.OpenOrCreate, FileAccess.Write))
        {
            netStream.CopyTo(fs);
        }
        netStream.Close();
    }

但是这个protion失败了。

 NetworkStream netStream = client.GetStream();
        //  FileName is taken at run time on button click from textbox.

        using (FileStream fs = new FileStream(@"D:\John\FYL\"+FileName, FileMode.OpenOrCreate, FileAccess.Write))
        {
            netStream.CopyTo(fs);
        }
        netStream.Close();
    }

现在,当我检查另一个案例时,使用 File.Create 并在运行时获取 FileName 它可以工作。

    FileStream output = File.Create(@"D:\John\" + FileName)

我很怀疑,因为我必须在运行时从“浏览”对话框中获取保存位置,但为什么 FileStream fs = new FileStream(@"D:\John\FYL\+FileName 会引发 System.IO.DirectoryNotFoundExceptionSystem.UnauthorizedAcessException 等异常,尽管我更改了本地驱动器的安全设置。

线程是否会影响这一切,因为这段代码是在运行时加载的代码的一部分,而浏览是一个点击事件?

【问题讨论】:

    标签: c# winforms file-io client-server system.io.file


    【解决方案1】:

    在尝试创建文件之前,您需要确保目录存在。

    NetworkStream netStream = client.GetStream();
    
    if (!Directory.Exists(@"D:\John\FYL\" + FileName)) {
        Directory.CreateDirectory(@"D:\John\FYL\" + FileName);
    }
    
    using (FileStream fs = new
        FileStream(@"D:\John\FYL\" + FileName, FileMode.OpenOrCreate, FileAccess.Write))
    {
        netStream.CopyTo(fs);
    }
    
    netStream.Close();
    

    您可能还想检查变量FileName 的格式是否正确。由于您已经提供了尾部反斜杠"D:\John\FYL\",请检查FileName 是否不是\File1.mp4,这将连接到"D:\John\FYL\\File1.mp4",这是不正确的。

    【讨论】:

    • 我在一个从 form_load() 启动的线程中使用此代码。它是否应该等待browse_click 来创建FileStream()?。
    • 顺便说一句,你的建议返回了An unhandled exception of type 'System.IO.DirectoryNotFoundException' occurred in mscorlib.dll Additional information: Could not find a part of the path 'D:\John\FYL\'.
    • @Khan 你是说代码在Browse按钮被点击之前执行?这意味着FileName 变量甚至还没有加载?
    • FileNameBrowse_Click 之后从textBox.text 获取其值
    • 此行为是否是此操作的结果?
    【解决方案2】:

    您是否尝试过查看 FileName 的值?可能它给出了错误的值。 如果 File name 只包含文件名,那么一定要给出文件名和文件扩展名,如果没有提供任何扩展名,你的程序将把文件名当作它无法找到的目录扩展名。

    如果文件名包含名称以及目录层次结构,那么您只是将一个目录连接到“D:\John\”目录,这又是错误的。

    【讨论】:

      猜你喜欢
      • 2021-12-20
      • 1970-01-01
      • 1970-01-01
      • 2013-12-10
      • 2014-01-21
      • 1970-01-01
      • 2015-03-19
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多