4

I've put 3 especially large SQL queries within my Visual Studio project, under a folder "Queries" that is in the project directory (not the solution). Is there an eloquent way to access these files? I was hoping that something like @"Queries/firstSqlQuery.sql would work.

Specifying the full path, like with @"C:\\Users\John\Documents\VisualStudio2010\Projects\MySolution\MyProject\Queries\firstSqlQuery.sql is something I'd really rather not do, since it requires me to go back into code and fix the path, should the application move.

EDIT: For some reason, the page is looking for the files in C:\\Program Files(x86)\Common Files\Microsoft Shared\DevServer\Queries\firstSqlQuery.sql. Why is it looking in this location, when the executable directory is different?

4

3 回答 3

3

你可以做这样的事情......如果它在项目之外。(当我最初阅读这篇文章时——我误读并认为它在我假设包含该项目的解决方案目录中)——

var pathToBin = Assembly.GetExecutingAssembly().Location;
var directoryInfoOfBin = new DirectoryInfo(pathToBin);
var solutionDirectory = directory.Parent().Parent();
var pathToSolution = solutionDirectory.FullName;

但如果它在项目中,这要简单得多

System.Web.HttpContext.Current.Server.MapPath("~/Queries/firstSqlQuery");
于 2013-06-07T12:42:45.937 回答
2

有很多方法可以处理这个问题,但是你必须首先收集一个基本的理解。发行类似的东西@"Queries/..."本身并不会做任何事情。您需要利用System.IO命名空间来执行 IO 操作。

有了这部分基础,当你发出这样的命令时,让我们再打一些:

File.ReadAllText("firstSqlQuery.sql");

隐含的路径是Working Directory执行代码的程序集的路径。在 Visual Studio 中调试应用程序时,尤其是 ASP.NET 应用程序,默认情况bin下,该目录位于项目目录下。因此,如果您确实想访问该文件夹,则必须执行以下操作:Queries

File.ReadAllText(@"..\Queries\firstSqlQuery.sql");

所以,这是处理它的一种方法。

bin另一种处理方法是在每次构建项目时通过查看文件属性(例如 create a )将文件复制到文件夹中Post Build Event,但这比我认为您正在寻找的工作要多。

同样,这里的关键是了解您从哪个目录开始。

最后,值得注意的一件事是,如果您利用目录结构,您需要确保将Queries文件夹部署到实时站点。这可能是不言而喻的,但我以前见过人们遇到过这个确切的问题。

于 2013-06-07T12:43:48.913 回答
0

您可以确保在进行构建时将查询文件复制到输出目录并从那里读取文件,而无需设置路径。

于 2013-06-07T12:44:02.573 回答