I am trying to enumerate through files on my computer using the below code but everytime it hits a file or dir that I don't have permission to read it throws an exception. Is there any way I can continue searching after the exception has been thrown? I know some people have had similar issues but is there any other way of doing this other than checking every file/folder individually?
try
{
string[] files = Directory.GetFiles(#"C:\", "*.*",SearchOption.AllDirectories);
foreach (string file in files)
{
Console.WriteLine(file);
}
}
catch
{
}
Thanks for any help as this is driving me mad!
I came across the same problem just today. I hacked together the following code. If you want to use it in a real product you might need to improve the error handling. Since this was for a one-shot script I didn't care much.
static IEnumerable<string> EnumerateFilesRecursive(string root,string pattern="*")
{
var todo = new Queue<string>();
todo.Enqueue(root);
while (todo.Count > 0)
{
string dir = todo.Dequeue();
string[] subdirs = new string[0];
string[] files = new string[0];
try
{
subdirs = Directory.GetDirectories(dir);
files = Directory.GetFiles(dir, pattern);
}
catch (IOException)
{
}
catch (System.UnauthorizedAccessException)
{
}
foreach (string subdir in subdirs)
{
todo.Enqueue(subdir);
}
foreach (string filename in files)
{
yield return filename;
}
}
}
To use it you can either:
string[] files = EnumerateFilesRecursive(#"C:\").ToArray();//Note the ToArray()
foreach (string file in files)
{
Console.WriteLine(file);
}
which first enumerates all files, stores all file names in memory and only then displays them. Alternatively you can:
IEnumerable<string> files = EnumerateFilesRecursive(#"C:\");//Note that there is NO ToArray()
foreach (string file in files)
{
Console.WriteLine(file);
}
Which writes while enumerating and thus doesn't need to keep all filenames in memory at the same time.
Here is some utility code based on Windows API that enumerates file system entries without throwing/catching exceptions.
Sample usage:
...
foreach (var fi in Utilities.EnumerateFileSystemEntries(#"c:\windows\system32", DirectoryEnumerateOptions.Recursive))
{
Console.WriteLine(fi.FullName);
}
...
Utility classes:
[Flags]
public enum DirectoryEnumerateOptions
{
None = 0x0,
Recursive = 0x1,
ThrowErrors = 0x2, // if you really want it
ExpandEnvironmentVariables = 0x4,
}
public static class Utilities
{
public static IEnumerable<FileSystemInfo> EnumerateFileSystemEntries(string directoryPath, DirectoryEnumerateOptions options = DirectoryEnumerateOptions.None)
{
if (directoryPath == null)
throw new ArgumentNullException(nameof(directoryPath));
if (!Path.IsPathRooted(directoryPath))
{
directoryPath = Path.GetFullPath(directoryPath);
}
return EnumerateFileSystemEntriesPrivate(directoryPath, options);
}
private static IEnumerable<FileSystemInfo> EnumerateFileSystemEntriesPrivate(string directoryPath, DirectoryEnumerateOptions options = DirectoryEnumerateOptions.None)
{
if (!Directory.Exists(directoryPath))
yield break;
var findPath = Normalize(directoryPath, options.HasFlag(DirectoryEnumerateOptions.ExpandEnvironmentVariables));
if (!findPath.EndsWith("*"))
{
findPath = Path.Combine(findPath, "*");
}
var h = FindFirstFile(findPath, out var data);
if (h == INVALID_HANDLE_VALUE)
{
if (options.HasFlag(DirectoryEnumerateOptions.ThrowErrors))
throw new Win32Exception(Marshal.GetLastWin32Error());
yield break;
}
if (Include(ref data))
{
yield return ToInfo(ref data, directoryPath);
if (options.HasFlag(DirectoryEnumerateOptions.Recursive) && data.fileAttributes.HasFlag(FileAttributes.Directory))
{
foreach (var wfd in EnumerateFileSystemEntriesPrivate(Path.Combine(directoryPath, data.cFileName), options))
{
yield return wfd;
}
}
}
do
{
if (!FindNextFile(h, out data))
{
if (Marshal.GetLastWin32Error() == ERROR_NO_MORE_FILES)
{
FindClose(h);
break;
}
continue;
}
if (Include(ref data))
{
yield return ToInfo(ref data, directoryPath);
if (options.HasFlag(DirectoryEnumerateOptions.Recursive) && data.fileAttributes.HasFlag(FileAttributes.Directory))
{
foreach (var wfd in EnumerateFileSystemEntriesPrivate(Path.Combine(directoryPath, data.cFileName), options))
{
yield return wfd;
}
}
}
}
while (true);
}
private static bool Include(ref WIN32_FIND_DATA data) => data.cFileName != "." && data.cFileName != "..";
private static FileSystemInfo ToInfo(ref WIN32_FIND_DATA data, string directoryPath)
{
if (data.fileAttributes.HasFlag(FileAttributes.Directory))
return new FileInfo(Path.Combine(directoryPath, data.cFileName));
return new DirectoryInfo(Path.Combine(directoryPath, data.cFileName));
}
private static string Normalize(string path, bool expandEnvironmentVariables)
{
if (path == null)
return null;
string expanded;
if (expandEnvironmentVariables)
{
expanded = Environment.ExpandEnvironmentVariables(path);
}
else
{
expanded = path;
}
if (expanded.StartsWith(_prefix))
return expanded;
if (expanded.StartsWith(#"\\"))
return _uncPrefix + expanded.Substring(2);
return _prefix + expanded;
}
[DllImport("kernel32", SetLastError = true, CharSet = CharSet.Unicode)]
private static extern IntPtr FindFirstFile(string lpFileName, out WIN32_FIND_DATA lpFindFileData);
[DllImport("kernel32", SetLastError = true)]
private static extern bool FindClose(IntPtr hFindFile);
[DllImport("kernel32", SetLastError = true, CharSet = CharSet.Unicode)]
private static extern bool FindNextFile(IntPtr hFindFile, out WIN32_FIND_DATA lpFindFileData);
#pragma warning disable IDE1006 // Naming Styles
private const int ERROR_NO_MORE_FILES = 18;
private static readonly IntPtr INVALID_HANDLE_VALUE = new IntPtr(-1);
#pragma warning restore IDE1006 // Naming Styles
private const string _prefix = #"\\?\";
private const string _uncPrefix = _prefix + #"UNC\";
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
internal struct WIN32_FIND_DATA
{
public FileAttributes fileAttributes;
public uint ftCreationTimeLow;
public uint ftCreationTimeHigh;
public uint ftLastAccessTimeLow;
public uint ftLastAccessTimeHigh;
public uint ftLastWriteTimeLow;
public uint ftLastWriteTimeHigh;
public uint fileSizeHigh;
public uint fileSizeLow;
public uint dwReserved0;
public uint dwReserved1;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 260)]
public string cFileName;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 14)]
public string cAlternateFileName;
}
}
Related
I need to download files from a server to a shared drive directory, creating the directory if it doesn't exist. There are a few things making this more complicated:
I do not have write access (nor does the account that will run the job in UAT/Prod) to the shared drive directory.
The Service account that does have write access does not have any privileges anywhere but the shared drive directory.
I attempt to impersonate, as so:
class Impersonation
{
const int LOGON32_LOGON_NETWORK = 3;
const int LOGON_TYPE_NEW_CREDENTIALS = 9;
const int LOGON32_PROVIDER_WINNT50 = 3;
[DllImport("advapi32.dll", SetLastError = true)]
public static extern bool LogonUser(string pszUsername, string pszDomain, string pszPassword, int dwLogonType, int dwLogonProvider, ref IntPtr phToken);
[DllImport("kernel32.dll", CharSet = CharSet.Auto)]
public extern static bool CloseHandle(IntPtr handle);
public static void Impersonate(string domain, string user, string password, Action act)
{
//if no user specified, don't impersonate
if (user.Trim() == "")
{
act();
return;
}
WindowsImpersonationContext impersonationContext = null;
IntPtr token = IntPtr.Zero;
try
{
//if no domain specified, default it to current machine
if (domain.Trim() == "")
{
domain = System.Environment.MachineName;
}
bool result = LogonUser(user, domain, password, LOGON_TYPE_NEW_CREDENTIALS, LOGON32_PROVIDER_WINNT50, ref token);
WindowsIdentity wi = new WindowsIdentity(token);
impersonationContext = WindowsIdentity.Impersonate(token);
act();
}
catch (Exception ex)
{
if (impersonationContext != null)
{
impersonationContext.Undo();
impersonationContext = null;
}
//if something went wrong, try it as the running user just in case
act();
}
finally
{
if (impersonationContext != null)
{
impersonationContext.Undo();
impersonationContext = null;
}
if (token != IntPtr.Zero)
{
CloseHandle(token);
token = IntPtr.Zero;
}
}
}
}
And a piece of the the actual calling code is (in another class):
private static void CreateDirectoryIfNotExist(string directory, string domain, string username, string password)
{
Impersonation.Impersonate(domain, username, password, () => CreateIfNotExist(directory));
}
private static void CreateIfNotExist(string dir)
{
if (!Directory.Exists(dir))
{
Directory.CreateDirectory(dir);
}
}
If I run it with the proper login info for the service account, I get an Exception on the Directory.CreateDirectory(string) call:
{System.IO.IOException: This user isn't allowed to sign in to this computer.}
I'm guessing this means the service account isn't allowed to log in to the executing machine, which I already knew. But really, there's no reason it needs to log in to the executing machine. Is there a way I can use impersonation to log on to a remote machine and execute the commands from there?
You cannot do it with impersonation if the account cannot log on. Impersonation requires the thread to run under the user credentials. That is why the LogonUser fails.
You can use the WNetAddConnection2 function that is used to establish a connection to a network resource.
Here is a sample for your CreateDirectoryIfNotExist function using this approach:
public static void CreateDirectoryIfNotExists(string directory, string sharePath, string username, string password)
{
NETRESOURCE nr = new NETRESOURCE();
nr.dwType = ResourceType.RESOURCETYPE_DISK;
nr.lpLocalName = null;
nr.lpRemoteName = sharePath;
nr.lpProvider = null;
int result = WNetAddConnection2(nr, password, username, 0);
string directoryFullPath = Path.Combine(sharePath, directory);
if (!Directory.Exists(directoryFullPath))
{
Directory.CreateDirectory(directoryFullPath);
}
}
To be able to do the system call you need also the following definitions from pinvoke.net.
[StructLayout(LayoutKind.Sequential)]
private class NETRESOURCE
{
public ResourceScope dwScope = 0;
public ResourceType dwType = 0;
public ResourceDisplayType dwDisplayType = 0;
public ResourceUsage dwUsage = 0;
[MarshalAs(UnmanagedType.LPStr)] public string lpLocalName = null;
[MarshalAs(UnmanagedType.LPStr)] public string lpRemoteName = null;
[MarshalAs(UnmanagedType.LPStr)] public string lpComment = null;
[MarshalAs(UnmanagedType.LPStr)] public string lpProvider;
};
public enum ResourceScope
{
RESOURCE_CONNECTED = 1,
RESOURCE_GLOBALNET,
RESOURCE_REMEMBERED,
RESOURCE_RECENT,
RESOURCE_CONTEXT
};
public enum ResourceType
{
RESOURCETYPE_ANY,
RESOURCETYPE_DISK,
RESOURCETYPE_PRINT,
RESOURCETYPE_RESERVED
};
public enum ResourceUsage
{
RESOURCEUSAGE_CONNECTABLE = 0x00000001,
RESOURCEUSAGE_CONTAINER = 0x00000002,
RESOURCEUSAGE_NOLOCALDEVICE = 0x00000004,
RESOURCEUSAGE_SIBLING = 0x00000008,
RESOURCEUSAGE_ATTACHED = 0x00000010,
RESOURCEUSAGE_ALL = (RESOURCEUSAGE_CONNECTABLE | RESOURCEUSAGE_CONTAINER | RESOURCEUSAGE_ATTACHED),
};
public enum ResourceDisplayType
{
RESOURCEDISPLAYTYPE_GENERIC,
RESOURCEDISPLAYTYPE_DOMAIN,
RESOURCEDISPLAYTYPE_SERVER,
RESOURCEDISPLAYTYPE_SHARE,
RESOURCEDISPLAYTYPE_FILE,
RESOURCEDISPLAYTYPE_GROUP,
RESOURCEDISPLAYTYPE_NETWORK,
RESOURCEDISPLAYTYPE_ROOT,
RESOURCEDISPLAYTYPE_SHAREADMIN,
RESOURCEDISPLAYTYPE_DIRECTORY,
RESOURCEDISPLAYTYPE_TREE,
RESOURCEDISPLAYTYPE_NDSCONTAINER
};
public enum ResourceConnection
{
CONNECT_UPDATE_PROFILE = 1,
CONNECT_UPDATE_RECENT = 2,
CONNECT_TEMPORARY = 4,
CONNECT_INTERACTIVE = 8,
CONNECT_PROMPT = 0X10,
CONNECT_REDIRECT = 0X80,
CONNECT_CURRENT_MEDIA = 0X200,
CONNECT_COMMAND_LINE = 0X800,
CONNECT_CMD_SAVECRED = 0X1000,
CONNECT_CRED_RESET = 0X2000
};
[DllImport("mpr.dll", CharSet = System.Runtime.InteropServices.CharSet.Ansi)]
private static extern int WNetAddConnection2(NETRESOURCE lpNetResource,
[MarshalAs(UnmanagedType.LPStr)] string lpPassword,
[MarshalAs(UnmanagedType.LPStr)] string lpUserName, int dwFlags);
You can add this definitions to the same class as your function.
Here are also links to two older post which also use the same approach.
Accessing a Shared File (UNC) From a Remote, Non-Trusted Domain With Credentials
How do I access a file share programmatically
You can solve this problem like I solved it. Below are the steps:
Step 1: Open IIS. Then add a virtual directory in your web application.
Step 2: Then map your shared path with the virtual directory added in Step 1
Step 3: Now click on Connect as..
Step 4: Set the credential of your desired user by which you want to connect your shared path.
Step 5: Now the IIS configuration part is over and you need to start using src="Image/Image.png" in your html or start manipulating "SharedFolder/YourFile.ext".
I am working on a web application that has the following environment setup:
The website is designed to work in Chrome
The website depends on a Chrome Extension developed in-house and hosted on the Chrome Play Store
To make getting the extension easier, our systems team has setup the ExtensionInstallForcelist Group Policy (more information here http://dev.chromium.org/administrators/policy-list-3#ExtensionInstallForcelist). This makes it so Chrome can get the extension and update it as needed without manual user interaction
This is all setup on imaged devices (so separate devices, with separate browsers and group policies, that each get the extension on their own)
The problem I'm facing is when trying to use a Chromedriver instance with this group policy.
With the policy enabled, I am getting an error that says "Failed to load extension from: . (extension ID ) is blocked by the administrator." when running our tests.
This seems to happen because we add the extension to our Chromedriver through the Chrome Options (add Extension).
While I can manually turn off the Group Policy on our imaged devices to get around this, I was wondering if there is any setting I can add to the group policy to make it allow the installation of our extension in the Chromedriver?
I've tried a number of ways to get around this otherwise that didn't seem to work:
Command Line altering of the registry values set by the Group Policy - didn't work as, although altering the registry values worked, I still recevied the error on running tests
PowerShell altering of the group policy - won't work as it requires additional install of the Get Group Policy cmdlets
Using the GPMC C# libraries - the libraries seem very much out of date at this point (some only use .NET 2.0). I was able to setup some code to use the classes, but I receive a "reference missing" exception for creating a GPODomain object even though I have the reference in my solution
Thank you all in advance for any suggestions on getting making Chromedriver work with the force install group policy.
After a lot of looking at different answers around the web, I found this solution works.
Create a GroupPolicy class to handle interacting with it:
using Microsoft.Win32;
using Microsoft.Win32.SafeHandles;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace Automation.Core
{
[ComImport, Guid("EA502722-A23D-11d1-A7D3-0000F87571E3")]
internal class GPClass
{
}
[ComImport, Guid("EA502723-A23D-11d1-A7D3-0000F87571E3"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
public interface IGroupPolicyObject
{
uint New([MarshalAs(UnmanagedType.LPWStr)] string domainName, [MarshalAs(UnmanagedType.LPWStr)] string displayName, uint flags);
uint OpenDSGPO([MarshalAs(UnmanagedType.LPWStr)] string path, uint flags);
uint OpenLocalMachineGPO(uint flags);
uint OpenRemoteMachineGPO([MarshalAs(UnmanagedType.LPWStr)] string computerName, uint flags);
uint Save([MarshalAs(UnmanagedType.Bool)] bool machine, [MarshalAs(UnmanagedType.Bool)] bool add, [MarshalAs(UnmanagedType.LPStruct)] Guid extension, [MarshalAs(UnmanagedType.LPStruct)] Guid app);
uint Delete();
uint GetName([MarshalAs(UnmanagedType.LPWStr)] StringBuilder name, int maxLength);
uint GetDisplayName([MarshalAs(UnmanagedType.LPWStr)] StringBuilder name, int maxLength);
uint SetDisplayName([MarshalAs(UnmanagedType.LPWStr)] string name);
uint GetPath([MarshalAs(UnmanagedType.LPWStr)] StringBuilder path, int maxPath);
uint GetDSPath(uint section, [MarshalAs(UnmanagedType.LPWStr)] StringBuilder path, int maxPath);
uint GetFileSysPath(uint section, [MarshalAs(UnmanagedType.LPWStr)] StringBuilder path, int maxPath);
uint GetRegistryKey(uint section, out IntPtr key);
uint GetOptions(out uint options);
uint SetOptions(uint options, uint mask);
uint GetType(out IntPtr gpoType);
uint GetMachineName([MarshalAs(UnmanagedType.LPWStr)] StringBuilder name, int maxLength);
uint GetPropertySheetPages(out IntPtr pages);
}
public enum GroupPolicySection
{
Root = 0,
User = 1,
Machine = 2,
}
public abstract class GroupPolicyObject
{
protected const int MaxLength = 1024;
/// <summary>
/// The snap-in that processes .pol files
/// </summary>
private static readonly Guid RegistryExtension = new Guid(0x35378EAC, 0x683F, 0x11D2, 0xA8, 0x9A, 0x00, 0xC0, 0x4F, 0xBB, 0xCF, 0xA2);
/// <summary>
/// This application
/// </summary>
private static readonly Guid LocalGuid = new Guid(GetAssemblyAttribute<GuidAttribute>(Assembly.GetExecutingAssembly()).Value);
protected IGroupPolicyObject Instance = (IGroupPolicyObject) new GPClass();
static T GetAssemblyAttribute<T>(ICustomAttributeProvider assembly) where T : Attribute
{
object[] attributes = assembly.GetCustomAttributes(typeof(T), true);
if (attributes.Length == 0)
return null;
return (T)attributes[0];
}
public void Save()
{
var result = Instance.Save(true, true, RegistryExtension, LocalGuid);
if (result != 0)
{
throw new Exception("Error saving machine settings");
}
result = Instance.Save(false, true, RegistryExtension, LocalGuid);
if (result != 0)
{
throw new Exception("Error saving user settings");
}
}
public RegistryKey GetRootRegistryKey(GroupPolicySection section)
{
IntPtr key;
var result = Instance.GetRegistryKey((uint)section, out key);
if (result != 0)
{
throw new Exception(string.Format("Unable to get section '{0}'", Enum.GetName(typeof(GroupPolicySection), section)));
}
var handle = new SafeRegistryHandle(key, true);
return RegistryKey.FromHandle(handle, RegistryView.Default);
}
}
public class GroupPolicyObjectSettings
{
public readonly bool LoadRegistryInformation;
public readonly bool Readonly;
public GroupPolicyObjectSettings(bool loadRegistryInfo = true, bool readOnly = false)
{
LoadRegistryInformation = loadRegistryInfo;
Readonly = readOnly;
}
private const uint RegistryFlag = 0x00000001;
private const uint ReadonlyFlag = 0x00000002;
internal uint Flag
{
get
{
uint flag = 0x00000000;
if (LoadRegistryInformation)
{
flag |= RegistryFlag;
}
if (Readonly)
{
flag |= ReadonlyFlag;
}
return flag;
}
}
}
public class ComputerGroupPolicyObject : GroupPolicyObject
{
public readonly bool IsLocal;
public ComputerGroupPolicyObject(GroupPolicyObjectSettings options = null)
{
options = options ?? new GroupPolicyObjectSettings();
var result = Instance.OpenLocalMachineGPO(options.Flag);
if (result != 0)
{
throw new Exception("Unable to open local machine GPO");
}
IsLocal = true;
}
public static void SetPolicySetting(string registryInformation, string settingValue, RegistryValueKind registryValueKind)
{
string valueName;
GroupPolicySection section;
string key = Key(registryInformation, out valueName, out section);
// Thread must be STA
Exception exception = null;
var t = new Thread(() =>
{
try
{
var gpo = new ComputerGroupPolicyObject();
using (RegistryKey rootRegistryKey = gpo.GetRootRegistryKey(section))
{
// Data can't be null so we can use this value to indicate key must be delete
if (settingValue == null)
{
using (RegistryKey subKey = rootRegistryKey.OpenSubKey(key, true))
{
if (subKey != null)
{
subKey.DeleteValue(valueName);
}
}
}
else
{
using (RegistryKey subKey = rootRegistryKey.CreateSubKey(key))
{
subKey.SetValue(valueName, settingValue, registryValueKind);
}
}
}
gpo.Save();
}
catch (Exception ex)
{
exception = ex;
}
});
t.SetApartmentState(ApartmentState.STA);
t.Start();
t.Join();
if (exception != null)
throw exception;
}
public static object GetPolicySetting(string registryInformation)
{
string valueName;
GroupPolicySection section;
string key = Key(registryInformation, out valueName, out section);
// Thread must be STA
object result = null;
var t = new Thread(() =>
{
var gpo = new ComputerGroupPolicyObject();
using (RegistryKey rootRegistryKey = gpo.GetRootRegistryKey(section))
{
// Data can't be null so we can use this value to indicate key must be delete
using (RegistryKey subKey = rootRegistryKey.OpenSubKey(key, true))
{
if (subKey == null)
{
result = null;
}
else
{
result = subKey.GetValue(valueName);
}
}
}
});
t.SetApartmentState(ApartmentState.STA);
t.Start();
t.Join();
return result;
}
public static string Key(string registryInformation, out string value, out GroupPolicySection section)
{
// Parse parameter of format HKCU\Software\Policies\Microsoft\Windows\Personalization!NoChangingSoundScheme
string[] split = registryInformation.Split('!');
string key = split[0];
string hive = key.Substring(0, key.IndexOf('\\'));
key = key.Substring(key.IndexOf('\\') + 1);
value = split[1];
if (hive.Equals(#"HKLM", StringComparison.OrdinalIgnoreCase)
|| hive.Equals(#"HKEY_LOCAL_MACHINE", StringComparison.OrdinalIgnoreCase))
{
section = GroupPolicySection.Machine;
}
else
{
section = GroupPolicySection.User;
}
return key;
}
}
}
Then turn off the Force Install Chrome Extension Group Policy with a call like this:
[STAThread]
private static bool DisabledChromeExtensionGPO()
{
var PolicyExists = ComputerGroupPolicyObject.GetPolicySetting(#"HKEY_LOCAL_MACHINE\SOFTWARE\Policies\Google\Chrome\ExtensionInstallForcelist!1");
if (PolicyExists != null)
{
ComputerGroupPolicyObject.SetPolicySetting(#"HKEY_LOCAL_MACHINE\SOFTWARE\Policies\Google\Chrome\ExtensionInstallForcelist!1", "null", RegistryValueKind.String);
}
return true;
}
While the policy will still have its key in regedit listed, the value of the key will be set to null.
Setting the value to null allowed the Chrome Driver to load our local Chrome Extension file without issue at this point.
On Linux using MONO.
How do I use C# to pair a port number to a service ?
example:
port 80 = http
port 443 = https
and output it to the console, I need this for a simple port scanner I built.
I know this function exists in ruby:
Socket.getservbyport(80, "tcp")
Mono Linux version
I had a bit of time on my hands so set up Mono on my Ubuntu Linux box to test with. The Mono PInvoke implementation of getservbyport() and getservbyname() is simpler than on Windows (just load libc which has the networking stuff built in). Here's the example code for reference in case anyone ever wants it ;)
namespace SocketUtil
{
using System;
using System.Net;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Runtime.Serialization;
[Serializable]
public class SocketUtilException : Exception
{
public SocketUtilException()
{
}
public SocketUtilException(string message)
: base(message)
{
}
public SocketUtilException(string message, Exception inner)
: base(message, inner)
{
}
protected SocketUtilException(
SerializationInfo info, StreamingContext context)
: base(info, context)
{
}
}
public static class SocketUtil
{
[StructLayoutAttribute(LayoutKind.Sequential)]
public struct servent
{
public string s_name;
public IntPtr s_aliases;
public ushort s_port;
public string s_proto;
}
[DllImport("libc", SetLastError = true, CharSet = CharSet.Ansi)]
private static extern IntPtr getservbyname(string name, string proto);
[DllImport("libc", SetLastError = true, CharSet = CharSet.Ansi)]
private static extern IntPtr getservbyport(ushort port, string proto);
public static string GetServiceByPort(ushort port, string protocol, out List<string> aliases)
{
var netport = unchecked((ushort)IPAddress.HostToNetworkOrder(unchecked((short)port)));
var result = getservbyport(netport, protocol);
if (IntPtr.Zero == result)
{
throw new SocketUtilException(
string.Format("Could not resolve service for port {0}", port));
}
var srvent = (servent)Marshal.PtrToStructure(result, typeof(servent));
aliases = GetAliases(srvent);
return srvent.s_name;
}
private static List<string> GetAliases(servent srvent)
{
var aliases = new List<string>();
if (srvent.s_aliases != IntPtr.Zero)
{
IntPtr cb;
for (var i = 0;
(cb = Marshal.ReadIntPtr(srvent.s_aliases, i)) != IntPtr.Zero;
i += Marshal.SizeOf(cb))
{
aliases.Add(Marshal.PtrToStringAnsi(cb));
}
}
return aliases;
}
public static ushort GetServiceByName(string service, string protocol, out List<string> aliases)
{
var result = getservbyname(service, protocol);
if (IntPtr.Zero == result)
{
throw new SocketUtilException(
string.Format("Could not resolve port for service {0}", service));
}
var srvent = (servent)Marshal.PtrToStructure(result, typeof(servent));
aliases = GetAliases(srvent);
var hostport = IPAddress.NetworkToHostOrder(unchecked((short)srvent.s_port));
return unchecked((ushort)hostport);
}
}
class Program
{
static void Main(string[] args)
{
try
{
List<string> aliases;
var port = SocketUtil.GetServiceByName("https", "tcp", out aliases);
Console.WriteLine("https runs on port {0}", port);
foreach (var alias in aliases)
{
Console.WriteLine(alias);
}
Console.WriteLine("Reverse call:{0}", SocketUtil.GetServiceByPort(port, "tcp", out aliases));
}
catch (SocketUtilException exception)
{
Console.WriteLine(exception.Message);
if (exception.InnerException != null)
{
Console.WriteLine(exception.InnerException.Message);
}
}
}
}
}
Windows Version
Update: Saw too late that poster had added a Linux and Mono tag after asking the question so wrote a Windows implementation. On Linux use the Mono version in the second post.
Mohammad's solution is more portable than the alternative in many ways. getservbyname() and getservbyport() are platform-dependent and require using P/Invoke to use with c# on Windows and most likely on Mono as well.
To implement the code below in Mono you'll need to PInvoke using the platform specific APIs (the header would be netdb.h) - note that WSAStartUp() and WSACleanUp() are windows-specific socket initialization functions which are irrelevant on a Linux system. Don't have mono setup at the moment so can't provide a linux-specific solution but if you're willing to jump through the hoops here's a windows (32-bit) example to base your code on:
namespace SocketTest
{
using System;
using System.Net;
using System.Net.Sockets;
using System.Runtime.InteropServices;
using System.Runtime.Serialization;
[Serializable]
public class SocketUtilException : Exception
{
public SocketUtilException()
{
}
public SocketUtilException(string message)
: base(message)
{
}
public SocketUtilException(string message, Exception inner)
: base(message, inner)
{
}
protected SocketUtilException(
SerializationInfo info, StreamingContext context)
: base(info, context)
{
}
}
public static class SocketUtil
{
private const int WSADESCRIPTION_LEN = 256;
private const int WSASYSSTATUS_LEN = 128;
[StructLayout(LayoutKind.Sequential)]
public struct WSAData
{
public short wVersion;
public short wHighVersion;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = WSADESCRIPTION_LEN+1)]
public string szDescription;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = WSASYSSTATUS_LEN+1)]
public string wSystemStatus;
[Obsolete("Ignored when wVersionRequested >= 2.0")]
public ushort wMaxSockets;
[Obsolete("Ignored when wVersionRequested >= 2.0")]
public ushort wMaxUdpDg;
public IntPtr dwVendorInfo;
}
[StructLayoutAttribute(LayoutKind.Sequential)]
public struct servent
{
public string s_name;
public IntPtr s_aliases;
public short s_port;
public string s_proto;
}
private static ushort MakeWord ( byte low, byte high)
{
return (ushort)((ushort)(high << 8) | low);
}
[DllImport("ws2_32.dll", CharSet = CharSet.Auto, ExactSpelling = true, SetLastError = true)]
private static extern int WSAStartup(ushort wVersionRequested, ref WSAData wsaData);
[DllImport("ws2_32.dll", CharSet = CharSet.Auto, ExactSpelling = true, SetLastError = true)]
private static extern int WSACleanup();
[DllImport("ws2_32.dll", SetLastError = true, CharSet = CharSet.Ansi)]
private static extern IntPtr getservbyname(string name, string proto);
[DllImport("ws2_32.dll", SetLastError = true, CharSet = CharSet.Ansi)]
private static extern IntPtr getservbyport(short port, string proto);
public static string GetServiceByPort(short port, string protocol)
{
var wsaData = new WSAData();
if (WSAStartup(MakeWord(2, 2), ref wsaData) != 0)
{
throw new SocketUtilException("WSAStartup",
new SocketException(Marshal.GetLastWin32Error()));
}
try
{
var netport = Convert.ToInt16(IPAddress.HostToNetworkOrder(port));
var result = getservbyport(netport, protocol);
if (IntPtr.Zero == result)
{
throw new SocketUtilException(
string.Format("Could not resolve service for port {0}", port),
new SocketException(Marshal.GetLastWin32Error()));
}
var srvent = (servent)Marshal.PtrToStructure(result, typeof(servent));
return srvent.s_name;;
}
finally
{
WSACleanup();
}
}
public static short GetServiceByName(string service, string protocol)
{
var wsaData = new WSAData();
if(WSAStartup(MakeWord(2,2), ref wsaData) != 0)
{
throw new SocketUtilException("WSAStartup",
new SocketException(Marshal.GetLastWin32Error()));
}
try
{
var result = getservbyname(service, protocol);
if (IntPtr.Zero == result)
{
throw new SocketUtilException(
string.Format("Could not resolve port for service {0}", service),
new SocketException(Marshal.GetLastWin32Error()));
}
var srvent = (servent)Marshal.PtrToStructure(result, typeof(servent));
return Convert.ToInt16(IPAddress.NetworkToHostOrder(srvent.s_port));
}
finally
{
WSACleanup();
}
}
}
class Program
{
static void Main(string[] args)
{
try
{
var port = SocketUtil.GetServiceByName("http", "tcp");
Console.WriteLine("http runs on port {0}", port);
Console.WriteLine("Reverse call:{0}", SocketUtil.GetServiceByPort(port, "tcp"));
}
catch(SocketUtilException exception)
{
Console.WriteLine(exception.Message);
if(exception.InnerException != null)
{
Console.WriteLine(exception.InnerException.Message);
}
}
}
}
On Windows there is a "services" file which is located at System32\Drivers\Etc\ folder. I have written the following code to parse it. You can use it to find information on any port you want:
class Program
{
static void Main(string[] args)
{
var services = ReadServicesFile();
// For example, I want to find information about port 443 of TCP service
var port443Info = services.FirstOrDefault(s => s.Port == 443 && s.Type.Equals("tcp"));
if (port443Info != null)
{
Console.WriteLine("TCP Port = {0}, Service name = {1}", port443Info.Port, port443Info.Name);
}
}
static List<ServiceInfo> ReadServicesFile()
{
var sysFolder = Environment.GetFolderPath(Environment.SpecialFolder.System);
if (!sysFolder.EndsWith("\\"))
sysFolder += "\\";
var svcFileName = sysFolder + "drivers\\etc\\services";
var lines = File.ReadAllLines(svcFileName);
var result = new List<ServiceInfo>();
foreach (var line in lines)
{
if (string.IsNullOrEmpty(line) || line.StartsWith("#"))
continue;
var info = new ServiceInfo();
var index = 0;
// Name
info.Name = line.Substring(index, 16).Trim();
index += 16;
// Port number and type
var temp = line.Substring(index, 9).Trim();
var tempSplitted = temp.Split('/');
info.Port = ushort.Parse(tempSplitted[0]);
info.Type = tempSplitted[1].ToLower();
result.Add(info);
}
return result;
}
}
You will also need the following class declaration:
class ServiceInfo
{
public ushort Port { get; set; }
public string Name { get; set; }
public string Type { get; set; }
}
Hi I need to set proxy address of IE programmatically
Earlier I used to use this RedTomahawk.TORActivator
but it doesnot gives an option to set those proxies which requires username and password.
How can we set those proxies which needs username and passwords
Please provide examples like
void Setproxy(string ip,string port,string uname,string pwd)
{
///Code here
}
You could P/Invoke the WinHttpSetDefaultProxyConfiguration function.
UPDATE:
Including example as requested:
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
public struct WINHTTP_PROXY_INFO
{
public AccessType AccessType;
public string Proxy;
public string Bypass;
}
public enum AccessType
{
DefaultProxy = 0,
NamedProxy = 3,
NoProxy = 1
}
class Program
{
[DllImport("winhttp.dll", CharSet = CharSet.Unicode, SetLastError = true)]
public static extern bool WinHttpSetDefaultProxyConfiguration(ref WINHTTP_PROXY_INFO config);
static void Main()
{
var config = new WINHTTP_PROXY_INFO();
config.AccessType = AccessType.NamedProxy;
config.Proxy = "http://proxy.yourcompany.com:8080";
config.Bypass = "intranet.com";
var result = WinHttpSetDefaultProxyConfiguration(ref config);
if (!result)
{
throw new Win32Exception(Marshal.GetLastWin32Error());
}
else
{
Console.WriteLine("Successfully modified proxy settings");
}
}
}
How can I see the version of .net framework which renders my aspx page on remote server?
This outputs your version:
System.Environment.Version.ToString()
<%# Page language="C#" %>
<% Response.Write(".NET Framework Version: " + Environment.Version.ToString()); %>
Environment.Version
Enable Trace
Enabling Trace is another option view every details of rendered page, including .NET Version
Add Trace="true" in page directive
<%# Page Trace="true" %>
Scroll down to bottom and you will see rendered .NET Version
Actually, you all got the CLR version (but not really either, you actually get a string that is hard-coded in mscorlib.dll).
For the actual ASP.NET version, as you see it on the YSOD error pages, see here (they are NOT the same):
using System;
namespace MyElmahReplacement
{
public class MyVersionInfo
{
[System.Runtime.InteropServices.DllImport("kernel32.dll", CharSet = System.Runtime.InteropServices.CharSet.Unicode)]
private static extern IntPtr GetModuleHandle(string strModuleName);
[System.Runtime.InteropServices.DllImport("kernel32.dll", CharSet = System.Runtime.InteropServices.CharSet.Unicode)]
private static extern int GetModuleFileName(IntPtr ptrHmodule, System.Text.StringBuilder strFileName, int szeSize);
private static string GetFileNameFromLoadedModule(string strModuleName)
{
IntPtr hModule = GetModuleHandle(strModuleName);
if (hModule == IntPtr.Zero)
{
return null;
}
System.Text.StringBuilder sb = new System.Text.StringBuilder(256);
if (GetModuleFileName(hModule, sb, 256) == 0)
{
return null;
}
string strRetVal = sb.ToString();
if (strRetVal != null && strRetVal.StartsWith("\\\\?\\"))
strRetVal = strRetVal.Substring(4);
sb.Length = 0;
sb = null;
return strRetVal;
}
private static string GetVersionFromFile(string strFilename)
{
string strRetVal = null;
try
{
System.Diagnostics.FileVersionInfo fviVersion = System.Diagnostics.FileVersionInfo.GetVersionInfo(strFilename);
strRetVal = string.Format(System.Globalization.CultureInfo.InvariantCulture, "{0}.{1}.{2}.{3}", new object[] {
fviVersion.FileMajorPart,
fviVersion.FileMinorPart,
fviVersion.FileBuildPart,
fviVersion.FilePrivatePart
});
}
catch
{
strRetVal = "";
}
return strRetVal;
}
private static string GetVersionOfLoadedModule(string strModuleName)
{
string strFileNameOfLoadedModule = GetFileNameFromLoadedModule(strModuleName);
if (strFileNameOfLoadedModule == null)
return null;
return GetVersionFromFile(strFileNameOfLoadedModule);
}
public static string SystemWebVersion
{
get
{
return GetVersionFromFile(typeof(System.Web.HttpRuntime).Module.FullyQualifiedName);
}
}
public static bool IsMono
{
get
{
return Type.GetType("Mono.Runtime") != null;
}
}
public static string MonoVersion
{
get
{
string strMonoVersion = "";
Type tMonoRuntime = Type.GetType("Mono.Runtime");
if (tMonoRuntime != null)
{
System.Reflection.MethodInfo displayName = tMonoRuntime.GetMethod("GetDisplayName", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Static);
if (displayName != null)
strMonoVersion = (string)displayName.Invoke(null, null);
}
return strMonoVersion;
}
}
public static string DotNetFrameworkVersion
{
get
{
// values.Add(ExceptionPageTemplate.Template_RuntimeVersionInformationName, RuntimeHelpers.MonoVersion);
if (IsMono)
return MonoVersion;
// Return System.Environment.Version.ToString()
return GetVersionOfLoadedModule("mscorwks.dll");
}
}
public static string AspNetVersion
{
get
{
//values.Add(ExceptionPageTemplate.Template_AspNetVersionInformationName, Environment.Version.ToString());
if (IsMono)
return System.Environment.Version.ToString();
return GetVersionOfLoadedModule("webengine.dll");
}
}
public static bool IsVistaOrHigher
{
get
{
System.OperatingSystem osWindowsVersion = System.Environment.OSVersion;
return osWindowsVersion.Platform == System.PlatformID.Win32NT && osWindowsVersion.Version.Major >= 6;
}
}
public static void Test()
{
string ErrorPageInfo =
string.Format("Version Information: Microsoft .NET Framework Version: {0}; ASP.NET Version: {1}"
,DotNetFrameworkVersion
,AspNetVersion
);
Console.WriteLine(ErrorPageInfo);
}
} // End Class MyVersionInfo
} // End Namespace LegendenTest