Hardcoded filepaths c#
-
Hi all, I am experiencing a problem and I am not sure how to go about fixing it. I have an ASP.net app that is reading from a database. I have a default database file path hardcoded into my program that the program will use if the user does not specify a database file. When executed, if the program tries to access the default database it is failing. It seems like .net is adding a "C:" to my file path where it should be "\\dir1\\dir2\\DB.mdb" Can anyone help me out so that I can access the default database on the LAN. Thanks again :-D
-
Hi all, I am experiencing a problem and I am not sure how to go about fixing it. I have an ASP.net app that is reading from a database. I have a default database file path hardcoded into my program that the program will use if the user does not specify a database file. When executed, if the program tries to access the default database it is failing. It seems like .net is adding a "C:" to my file path where it should be "\\dir1\\dir2\\DB.mdb" Can anyone help me out so that I can access the default database on the LAN. Thanks again :-D
NEVER hard code a file path. Put the filepath in the
appSettings
section at the bottom of the Web.config file and useConfigurationSettings.AppSettings
to get it (defaulting to a hard-coded path if you like). When you do it this way, do not escape back-slashes (that's specific to a programming language - not strings). If you want to use a file from a share, then use"\\\\SERVER\\SHARE\\Dir1\\DB.mdb"
or@"\\SERVER\SHARE\Dir1\DB.mdb"
(notice the@
, which is a literal character identifier). Many of the IO members - unless you give them a URL - will assume a local path, which is why "C:" is being prepended to your string (well, the string isn't actually changed but the behavior is the same). If this file is in your virtual directory structure of your web application, 1) make sure it's protected from user's downloading it but so that the web application can access it, and 2) useServer.MapPath
orPage.MapPath
to map the virtual path (like /db/db.mdb) to a physical path (like C:\Inetpub\wwwroot\db\db.mdb).Microsoft MVP, Visual C# My Articles