Reading SQL query file from project directory

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

Specifying the full path, for example, using @"C:\\Users\John\Documents\VisualStudio2010\Projects\MySolution\MyProject\Queries\firstSqlQuery.sql is what I really would not want to do, since it requires me return to the code and fix the path if the application moves.

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

+4
source share
3 answers

You can do something like this ... if it is outside the project. (When I intimately read this - I misunderstood and thought that it was in the solution catalog that I assumed contained the project) -

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

but it is much easier if in the project

 System.Web.HttpContext.Current.Server.MapPath("~/Queries/firstSqlQuery"); 
+4
source

There are several ways to deal with this, but there is a fundamental understanding that you must first collect. Issuing something like @"Queries/..." is not going to do on its own. You need to use the System.IO namespace to perform I / O.

With that part of the foundation, albeit a little more, when you issue a command like this:

 File.ReadAllText("firstSqlQuery.sql"); 

the path that is implied is the Working Directory assembly that runs the code. When debugging an application in Visual Studio, especially an ASP.NET application, the bin directory, which is located in the project directory, is by default . So, if you want to access the Queries folder, you will need to do something like this:

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

so that is one way of processing it.

Another way to process this file would be to copy the file to the bin folder each time the project is built, if you look at the properties of the file (for example, create a Post Build Event ), but this works more than I think you're looking for.

Again, the key here is to understand which directory you are starting with.

Finally, it is worth noting that if you use the directory structure, you need to make sure that the Queries folder is deployed to the real site. This probably goes without saying, but I have seen people come across this exact problem before.

+1
source

You can make sure that your request files are copied to the output directory when you build and read the files from there without setting a path.

0
source

Source: https://habr.com/ru/post/1485031/


All Articles