個人檔案ThomasGoddard.com相片部落格網路更多 ![]() | 說明 |
|
|
19 August A fancy file pathWell it took me quite a while to figure this out so I thought it was worth documenting. I am sure many developers reference assemblies in a windows and web app at one point or another. The problem arrises when referencing the same assembly in a web app and you need to load a file specified in the web or app config, regardless of whether you're running in a windows or web app. So you might think accessing the assembly path using reflection is the full answer, that's what I thought too.
The actual solution is a mixture of that and the directory info class. For some reason the runtime is unable to locate the file path if you simply say:
string filePath = System.Reflection.Assembly.GetExecutingAssembly().CodeBase; File.Exists(filePath.Substring(8, filePath.LastIndexOf("/") + 1) + ConfigurationSettings.AppSettings["FileToGet.xml"]); It just doesn't work. If you try to access the file from windows explorer using the path data above, it works. So here's the cleanest solution I came up with: Assembly currentAssembly = Assembly.GetExecutingAssembly(); // This is a handy class. DirectoryInfo dir = new DirectoryInfo(Path.GetDirectoryName(currentAssembly.GetName().CodeBase.Substring(8))); // Now we have to take the returned file info and use it like so. FileInfo[] fileInfo = dir.GetFiles(ConfigurationSettings.AppSettings["ZipAreaCodeDataFile"]); if(fileInfo[0].Exists) areaZipCodeSchema.ReadXml(fileInfo[0].FullName); |
|
|