使用文件流从根目录文件夹读取文件

3

我有两个图像文件在我的文件夹中,我需要在程序中调用它们。我使用了:

AppDomain.curentDomain.baseDirectory + "Path and file name";

但是这会把我的文件放在bin目录中,我不想要那样做;我想从根目录中读取名为resource的文件夹,在那里保存我的文件并调用图像,请问如何编写代码?

在Windows Form应用程序中,我该如何从根目录读取文件?


AppDomain.CurrentDomain.BaseDirectory 和 Application.StartupPath 都在我的源代码的 bin/debug 目录中搜索。 - SurajSing
5个回答

5
为什么不使用Environment.CurrentDirectory
string path = Environment.CurrentDirectory + @"\Image1.jpg";
FileStream stream = new FileStream(path, FileMode.Open, FileAccess.Read);
Image image = Image.FromStream(stream);
stream.Close();

结合应用程序启动路径的方法要好得多。 :) Environment.CurrentDirectory 返回应用程序所在的当前路径。


为什么不使用Path.Combine()? - Casey

4
通常,您需要将这些项目设置为复制到 bin 文件夹中。在解决方案资源管理器/导航器中右键单击,选择属性,然后设置“复制到输出目录”。希望这样可以解决问题。

1
您可以使用这个:
System.IO.Path.Combine(Environment.CurrentDirectory, "Path to File")

Environment.CurrentDirectory会给你应用程序运行的路径。无论它是在Visual Studio中运行还是在应用程序部署时运行。

示例用法

// Read image1.jpg from application folder, into Image object
Image myImage = Image.FromFile(System.IO.Path.Combine(Environment.CurrentDirectory, "image1.jpg"));

我正在使用Windows应用程序,所以我不能使用Server.MapPath。那么有什么替代方法吗?帮帮忙吧。 - SurajSing
1
为什么不直接使用 Image.FromFile - Paolo Moretti

1
System.IO.Path.Combine(Application.StartupPath, @"..\..\YourFile.JPG")

返回您文件的绝对路径,但这仅在您使用VS时有效,因为在部署应用程序时没有bin\Debug。

string path = Path.Combine(Application.StartupPath, @"..\..\YourFile.JPG");
FileStream stream = new FileStream(path, FileMode.Open, FileAccess.Read);
Image image = Image.FromStream(stream);
stream.Close();

如果您计划将文件与exe一起发送,请在Solution Explorer中右键单击文件,选择包含在项目中,再次右键单击,选择属性并设置生成操作:无复制到输出目录:仅在较新时复制在属性窗口中,这将在每次构建时将文件复制到bin\Debug。然后您可以使用:
string path = Path.Combine(Application.StartupPath, "YourFile.JPG");

这将在VS中工作,并且在部署时也能正常运行。更好的做法是将文件嵌入到可执行文件中,以实现更干净的部署。


0

使用Server.MapPath("/path/to/file")


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接