How can I build Application.UserAppDataPath inside class libraries (that don't have an Application object)?
Winforms and Console Applications can use Application.UserAppDataPath
.
Wh开发者_开发知识库at if I want to build the same path from a dll? How can I do that?
I know that Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData)
would be the start...
Here is a method that will do what you want. This works in a WPF application without adding System.Windows.Forms.dll
public string GetUserAppDataPath()
{
string path = string.Empty;
System.Reflection.Assembly assm;
try
{
assm = System.Reflection.Assembly.GetEntryAssembly();
Type at = typeof(System.Reflection.AssemblyCompanyAttribute);
object[] r = assm.GetCustomAttributes(at, false);
System.Reflection.AssemblyCompanyAttribute ct = ((System.Reflection.AssemblyCompanyAttribute)(r[0]));
path = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
path += @"\" + ct.Company;
path += @"\" + assm.GetName().Version.ToString();
}
catch
{
}
return path;
}
You can use Application.UserAppDataPath from a DLL - simply add a reference to the System.Windows.Forms assembly from your DLL project.
However be aware that if your DLL is used in a Windows Service or Server application such as ASP.NET, it may run under an service account that does not have a profile - in this case UserAppDataPath won't exist. This is probably the main reason the Application class is in the System.Windows.Forms namespace.
Well, if you don't have an application object that you can use, you would start out with what you mentioned to get the "ApplicationData" folder path, then append the default folder structure on to that path.
CompanyName/ProductName
is the default additional items
精彩评论