如何在 C#.net 中读取 Windows 应用程序根目录中的文件?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12237104/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to read file in windows application root directory in C#.net?
提问by Kiran Solkar
If i use Application.StartupPath or AppDomain.CurrentDomain.BaseDirectory It Search in a bin\debug folder for the file but I have to use a folder from my root directory "Resources\imagefile.png" in ma c# .net project!
如果我使用 Application.StartupPath 或 AppDomain.CurrentDomain.BaseDirectory 它会在 bin\debug 文件夹中搜索文件,但我必须在 ma c# .net 项目中使用我的根目录“Resources\imagefile.png”中的文件夹!
Filestream fs;
fs = new Filestream(AppDomain.CurrentDomain.BaseDirectory + "folder\imagefile.png");
So how should write code to read file from my root directory in spite of using above code or a full path of the directory that is "@C:......." and even Server.MapPath is we cant use.
那么应该如何编写代码来从我的根目录读取文件,尽管使用了上面的代码或目录的完整路径是“@C:.......”,甚至我们不能使用 Server.MapPath 。
To get my application path ,but this gives something like C:\Projects\XYZ\ABC\bin\Debug
i don't want bin\Debug .Is there any way to achieve this ?
要获取我的应用程序路径,但这给出了类似 C:\Projects\XYZ\ABC\bin\Debug
我不想要 bin\Debug 。有什么办法可以做到这一点吗?
采纳答案by MoreAsh
By Using the Environment.CurrentDirectory
通过使用 Environment.CurrentDirectory
string yourpath = Environment.CurrentDirectory + @"\YourImage.jpg";
FileStream stream = new FileStream(yourpath, FileMode.Open, FileAccess.Read);
Image image = Image.FromStream(stream);
stream.Close();
回答by spender
Generally, you'd set those items to be copied into the bin folder. Right click in solution explorer/navigator, choose properties and set "Copy to output directory" to something different.
通常,您会将这些项目设置为复制到 bin 文件夹中。右键单击解决方案资源管理器/导航器,选择属性并将“复制到输出目录”设置为不同的内容。

