Как получить ProductName приложения в Silverlight - PullRequest
2 голосов
/ 02 марта 2011

Можно ли программно получить ProductName приложения Silverlight? Я ищу Silverlight-эквивалент этой инструкции WinForms / WPF:

string productName = System.Windows.Forms.Application.ProductName;

Спасибо

Ответы [ 3 ]

6 голосов
/ 02 марта 2011

Вы можете использовать следующий метод, но только если вы можете гарантировать, что вы вызываете его из сборки "entry".

public static void GetProductAndVersionEasy(out string productName, out Version productVersion)
{
  var callingAssembly = Assembly.GetCallingAssembly();

  // Get the product name from the AssemblyProductAttribute.
  //   Usually defined in AssemblyInfo.cs as: [assembly: AssemblyProduct("Hello World Product")]
  var assemblyProductAttribute = ((AssemblyProductAttribute[])callingAssembly.GetCustomAttributes(typeof(AssemblyProductAttribute),false)).Single();
  productName = assemblyProductAttribute.Product;

  // Get the product version from the assembly by using its AssemblyName.
  productVersion = new AssemblyName(callingAssembly.FullName).Version;
}

(Вы можете заменить GetCallingAssembly на GetExecutingAssembly, если метод присутствует в вашей записисборка).

Я также понял, как взломать эту информацию из .xap файла.Я загружаю байты основной сборки в память, затем читаю информацию о продукте и версии из последних нескольких байтов.Я должен был написать это, потому что мне был нужен метод, который я мог бы повторно использовать в базовой библиотеке, который можно вызывать из любого места (т.е. не из исполняющей или вызывающей сборки).

public static void GetProductAndVersionHack(
  out string productName, 
  out Version productVersion)
{
  // Get the name of the entry assembly
  var deployment = System.Windows.Deployment.Current;
  var entryPointAssembly = deployment.EntryPointAssembly + ".dll";

  // Get the assembly stream from the xap file
  StreamResourceInfo streamResourceInfo = Application.GetResourceStream(
    new Uri(
      entryPointAssembly, 
      UriKind.Relative));
  Stream stream = streamResourceInfo.Stream;

  // The VERSION_INFO struct as at the end of the file. Just read the last 1000 bytes or so from the stream
  // (Keep in mind that there are a lot of zeroes padded at the end of the stream. You should probably
  //  search for the real stream.Length after trimming them off)
  stream.Position = stream.Length - 1000; 
  StreamReader streamReader = new StreamReader(stream, Encoding.Unicode);
  string text = streamReader.ReadToEnd();

  // Split the string on the NULL character
  string[] strings = text.Split(
    new[] { '\0' }, 
    System.StringSplitOptions.RemoveEmptyEntries);

  // Get the Product Name (starts with unicode character \u0001)
  int ixProductName = strings.FindIndexOf(line => line.EndsWith("\u0001ProductName"));
  productName = ixProductName >= 0 ? strings[ixProductName + 1] : null;

  // Get the Product Version
  int ixProductVersion = strings.FindIndexOf(line => line.EndsWith("\u0001ProductVersion"));
  productVersion = ixProductVersion >= 0 ? Version.Parse(strings[ixProductVersion + 1]) : null;
}

public static int FindIndexOf<T>(
  this IEnumerable<T> source, 
  Func<T, bool> match)
{
  int i = -1;
  foreach (var item in source)
  {
    ++i;
    if (match(item)) return i;
  }
  return -1;
}
0 голосов
/ 04 марта 2011

Класс AssemblyName обеспечивает разбор свойства Assembly FullName.

Попробуйте это

string productName = (new System.Reflection.AssemblyName(this.GetType().Assembly.FullName)).Name;
0 голосов
/ 02 марта 2011

Не уверен, для какого устройства вы разрабатываете, но для WP7 silverlight, в папке Properties содержался файл с именем WMAppManifest.xml, а в Deployment> App их есть поле с названием Title, вы можете извлечь XML оттуда?

Надеюсь, это поможет.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...