I believe that many friends who use Asp.net + access as websites often have the following requirement: They want to obtain the physical path of the Access database in the database access layer class library, then splice the database connection string to perform database-related operations. on the website UI Layer, we can obtain the physical path of a website in many ways, such as: 1. request. physicalapplicationpath 2. request. mappath ("~ /"), But using these methods at the database access layer won't work...
Recently, I also have this requirement. I wrote the following method through "g.cn + self-study" and tested it (vs2008), so I will share it with you.
Using system. reflection;
Using system. IO; // do not forget to reference these two namespaces before using them.
/// <Summary>
/// Obtain the physical path of the Access Database
/// </Summary>
/// <Returns> </returns>
Public Static String Getdbpath ()
{
String Str = Assembly. getexecutingassembly (). location;
Str = Path. getdirectoryname (STR) + @" \__ Assemblyinfo _. ini " ;
Str = File. readalltext (STR, system. Text. encoding. Unicode );
Int Index = Str. indexof ( " File :/// " ) + 8 ;
Int Length = Str. indexof ( " /Bin " );
Str = Str. substring (index, Length - Index );
Str = Str. Replace ( ' / ' , ' \\ ' );
Str + = @" \ App_data \ mydb. MDB " ;
Return STR; // The physical path of the database is returned.
}
CodeExplanation:
1. String STR = assembly. getexecutingassembly (). location;
The obtained value is a temporary directory, for example, "C: \ WINDOWS \ Microsoft. net \ framework \ v2.0.50727 \ temporary ASP. net files \ thinclient \ ba81bed7 \ a7082081 \ Assembly \ dl3 \ 62f82680 \ 8345eb5b_37a6c901 \ ABC. DLL
2.STR = path. getdirectoryname (STR) + @ "\__ assemblyinfo _. ini ";
The key is this sentence.There is a "_ assemblyinfo _ in the same directory of the DLL file __. ini "file, open it with notepad and you will find the actual physical address of the package containing DLL. It's easy to know this.
3. Str = file. readalltext (STR, system. Text. encoding. Unicode );
Int Index = Str. indexof ("file: //") + 8;
Int length = Str. indexof ("/bin ");
STR = Str. substring (index, length-index );
STR = Str. Replace ('/','\\');
STR + = @ "\ app_data \ cms. mdb ";
The code is not explained in detail, that is, to read the INI file, find the actual physical path of the bin folder on the website, and then splice the database file name to obtain the physical path of the database, however, this method works only when the database file is in the same directory as the website.
Note: I am writingProgramA little accumulation in the process may make it easier for you to implement it.
--- Xiaohu 2009.04.15