هل هناك طريقة لتحويل برنامج .NET Framework محددات الملف إلى مسارات مع أحرف محركات الأقراص؟
سؤال
وكنت أبحث عن شيء مثل Server.MapPath في مجال ASP.NET لتحويل إخراج Assembly.GetExecutingAssembly (). تعليمات البرمجة الأساسية في مسار ملف مع حرف محرك الأقراص.
والتعليمة البرمجية التالية يعمل لحالات الاختبار حاولت:
private static string ConvertUriToPath(string fileName) { fileName = fileName.Replace("file:///", ""); fileName = fileName.Replace("/", "\\"); return fileName; }
ويبدو أن يجب أن يكون هناك شيء في .NET Framework التي من شأنها أن تكون أفضل بكثير - أنا فقط لم تكن قادرة على العثور عليه
المحلول
وحاول تبحث في Uri.LocalPath الممتلكات.
private static string ConvertUriToPath(string fileName)
{
Uri uri = new Uri(fileName);
return uri.LocalPath;
// Some people have indicated that uri.LocalPath doesn't
// always return the corret path. If that's the case, use
// the following line:
// return uri.GetComponents(UriComponents.Path, UriFormat.SafeUnescaped);
}
نصائح أخرى
وبحثت عن إجابة الكثير، والجواب الأكثر شعبية يستخدم <لأ href = "http://msdn.microsoft.com/en-us/library/system.uri.localpath.aspx" يختلط = " noreferrer نوفولو "> Uri.LocalPath . لكن System.Uri فشل في إعطاء LocalPath الصحيح إذا كان مسار يحتوي على "#". تفاصيل هي هنا أ >.
وبلدي الحل هو:
private static string ConvertUriToPath(string fileName)
{
Uri uri = new Uri(fileName);
return uri.LocalPath + Uri.UnescapeDataString(uri.Fragment).Replace('/', '\\');
}
هل يمكن أن مجرد استخدام Assembly.Location
؟
والموقع يمكن أن تكون مختلفة لتعليمات البرمجة الأساسية. مثلا عن الملفات في ASP.NET المرجح أن يتم حلها تحت ج: \ WINDOWS \ Microsoft.NET \ الإطار \ V2.0.50727 \ ASP.NET المؤقت. انظر "Assembly.CodeBase مقابل Assembly.Location" http://blogs.msdn.com/suzcook/archive/ 2003/06/26 / 57198.aspx