简体   繁体   English

C# 如何从项目根目录下的文件夹中读取文件

[英]C# how to read a file from a folder under the project root directory

When a form loads, I need to read a binary file under the /skubin folder and use it to populate a List .加载表单时,我需要读取/skubin文件夹下的二进制文件并使用它来填充List But I'm unable to open the file.但我无法打开文件。 When I do, I receive an error indicating that the file doesn't exist.当我这样做时,我收到一条错误消息,指出该文件不存在。

Below is the snippet of my code which I am trying to read the file from the folder.下面是我试图从文件夹中读取文件的代码片段。

string startpath = Application.StartupPath;           
string BinDir = Path.Combine(startpath, "skubin");
binNanme = Path.Combine(BinDir, "skuen.bin");
if (!File.Exists(binNanme))
{
    MessageBox.Show("Load bin fail");
    return;
}

When checking the BinDir value, instead of pointing to <project_root>/skubin , it's pointing to <project_root>/bin/Debug/skubin .检查BinDir值时,它不是指向<project_root>/skubin ,而是指向<project_root>/bin/Debug/skubin

I am not understanding why it is pointing to /bin/Debug folder.我不明白为什么它指向/bin/Debug文件夹。

Right-click on the.bin files in the skubin folder within solution explorer and select properties.右键单击解决方案资源管理器和 select 属性中 skubin 文件夹中的 .bin 文件。 Set "Copy to Output Directory" to "Copy Always".将“复制到 Output 目录”设置为“始终复制”。 This should solve your problem without making any code changes.这应该可以解决您的问题,而无需进行任何代码更改。 I am assuming you need those binary files at run-time.我假设您在运行时需要这些二进制文件。

When you compile your project, the results are placed into a {projectFolder}\bin\Debug, and when debugging, the application is run from there.当你编译你的项目时,结果被放置到一个 {projectFolder}\bin\Debug 中,并且在调试时,应用程序从那里运行。

You have 2 choices:您有 2 个选择:

Keep your code as-is, and in the properties window, mark your bin files as "Copy if newer" or "Copy always".保持您的代码原样,并在属性 window 中,将您的 bin 文件标记为“如果较新则复制”或“始终复制”。 This will copy the files into \bin\Debug\skubin when you compile, and access them from there.这将在您编译时将文件复制到 \bin\Debug\skubin 中,并从那里访问它们。 This would simulate deploying those files with your application.这将模拟使用您的应用程序部署这些文件。

-- Or -- - 或者 -

Modify your code to move up 2 directories from Application.StartupPath:修改您的代码以从 Application.StartupPath 上移 2 个目录:

string BinDir = Path.Combine(startpath, "..\\..\\skubin");

This would be the option if you're not thinking about deploying your application, and just running it from within your project folder.如果您不考虑部署应用程序,而只是从项目文件夹中运行它,这将是一个选项。

string filepath = Server.MapPath("~/skubin")
filepath= Path.Combine(filepath, "skuen.bin")
// open the file 

//if not in a controller,  you may use this

HttpContext.Current.Server.MapPath("~/skubin")

For Windows App, you may try Best way to get application folder path对于 Windows 应用程序,您可以尝试获取应用程序文件夹路径的最佳方法

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM