Here is a pretty simple class to get and set UserAgent.
using System.Runtime.InteropServices;
public static class UserAgent
{
[DllImport("urlmon.dll", CharSet = CharSet.Ansi)]
private static extern int UrlMkGetSessionOption(
int dwOption, StringBuilder pBuffer, int dwBufferLength, out int pdwBufferLength, int dwReserved);
[DllImport("urlmon.dll", CharSet = CharSet.Ansi)]
private static extern int UrlMkSetSessionOption(
int dwOption, string pBuffer, int dwBufferLength, int dwReserved);
const int URLMON_OPTION_USERAGENT = 0x10000001;
const int URLMON_OPTION_USERAGENT_REFRESH = 0x10000002;
const int URLMON_OPTION_URL_ENCODING = 0x10000004;
public static string Value
{
get
{
StringBuilder builder = new StringBuilder(512);
int returnLength;
UrlMkGetSessionOption(URLMON_OPTION_USERAGENT, builder, builder.Capacity, out returnLength, 0);
string value = builder.ToString();
return value;
}
set
{
UrlMkSetSessionOption(URLMON_OPTION_USERAGENT, value, value.Length, 0);
}
}
}
I had been looking for a decent way to get UserAgent from windows, as opposed to web, when I found Changing the user agent of the WebBrowser control
Inspired by the DLLImport of urlmon.dll, I looked in pinvoke.net, and found: http://pinvoke.net/default.aspx/urlmon.UrlMkGetSessionOption
Called by:
namespace GetUserAgent
{
class Program
{
// The name of the program that was started by user
// See: Assembly.GetEntryAssembly Method ()
// https://msdn.microsoft.com/en-us/library/system.reflection.assembly.getentryassembly.aspx
public static string ExecName
{
get
{
// The name of the executable that was started by user
return System.Reflection.Assembly.GetEntryAssembly().GetName().Name;
}
}
static void Main(string[] args)
{
foreach (string arg in args)
{
if ((arg == "/?")
|| (arg == "-?")
|| (arg == "--help"))
{
Console.Out.WriteLine(
"For /F \"tokens=*\" %%U In ('{0}') Do Set UserAgent=%%U",
ExecName);
return;
}
}
string userAgent = UserAgent.Value;
Console.Out.WriteLine(userAgent);
}
}
}
This generates the UserAgent value. Argument /? shows how to use it in a command script.