Ive done some google and stuff and i cant seem to figure this out.
Try Catch just doesnt work the way i would expect it to.
here is the code.
DirectoryEntry Discover = new DirectoryEntry("WinNT://Workgroup");
foreach (DirectoryEntry Node in Discover.Children)
{
try {
if (Node.Properties.Count > 0)
{
//you have access to the computer so yeah
}
}
catch(System.IO.FileNotFoundException err) {
var ErrorMesage = err.Message;
//Yeah you dont have access to this computer, lets write a subroutine to allow the user to put in a username and password to access it
}
so when i run this i get a epic box popup and say something stupid like
{"The network path was not found.\r\n":null}
Try this
try {
DirectoryEntry Discover = new DirectoryEntry("WinNT://Workgroup"); **//Error occured here**
foreach (DirectoryEntry Node in Discover.Children)
{
if (Node.Properties.Count > 0)
{
//you have access to the computer so yeah
}
}
}
catch(System.IO.FileNotFoundException err)
{
var ErrorMesage = err.Message;
//Yeah you dont have access to this computer, lets write a subroutine to allow the user to put in a username and password to access it
}
Now you are only attempt to check Node.Properties.Count access for errors, nothing more. Scope of the code DirectoryEntry Discover = new DirectoryEntry("WinNT://Workgroup"); has also to be put in try section.
Related
I am facing Unknown error (0x80005000) while adding user to LDAP server(Apache), the following is my code. Could anyone please let me know where I am doing mistake.
namespace TestMethods
{
public class Program
{
static void Main(string[] args)
{
var ldi = new LdapDirectoryIdentifier("localhost", 10389);
AddUser("username", "o=Company");
}
public static void AddUser(string username, string group)
{
try
{
DirectoryEntry dirEntry = new
DirectoryEntry("LDAP://localhost:10389,o=Company" + group);
Console.WriteLine("Added to the path");// Working
dirEntry.Invoke("Add", new object[] { username });//Received Exception here
dirEntry.CommitChanges();
Console.WriteLine("Added to the path");
dirEntry.Close();
}
catch(Exception e)
{
Console.WriteLine(e.Message);
}
}
}
}
I believe you should use a / to separate the server name from the DN in your path:
LDAP://localhost:10389/o=Company
The constructor of DirectoryEntry doesn't make any network requests, so your path isn't validated until you actually use it.
However, if you are not using Active Directory, then I don't think Invoke will work for you. The description of DirectoryEntry.Invoke says:
Calls a method on the native Active Directory Domain Services object.
Even then, I'm not sure which Add method you're trying to use.
The way to create a new object using DirectoryEntry is like this (assuming dirEntry is pointing to a path where it can be created):
var newUser = dirEntry.Children.Add($"uid={username}", "inetOrgPerson");
// Set other attributes like this:
// newUser.Properties["someAttribute"].Value = "something";
//Save - this is where the object is actually created
newUser.CommitChanges();
I've never used Apache's LDAP server (I know AD better), so you may have to edit the schema ("inetOrgPerson") if you need to.
So my problem is that I want to export my user account.
But inside C:\%user%\AppData\Local\ are System Hardlinks e.g.: Application Data which I obviously have no right to use them.
Is there a way to exclude those System Hardlinks from the copying process?
I'm not sure what you mean with hard links, but this might help you
foreach (var dir in new DirectoryInfo(#"c:\users\xxxxxx\AppData\Local").GetDirectories())
{
if (dir.Attributes.HasFlag(FileAttributes.ReparsePoint))
{
Console.WriteLine(dir.Name + " is symbolic, skip it");
}
else
{
//do your copy here
}
}
So I fixed the issue with Exception handling, doing it this way:
FileInfo[] sourceFiles = null;
try {
sourceFiles = new DirectoryInfo(sourcePath).GetFiles();
} catch (Exception ex) {
WriteLog(LogPath, ex + "");
return;
}
Since I'm a bit new to exception handling, I couldn't work it out for the first few hours on this problem.
I´m making a program to delete some files that I have on my PC. But when I try to do it, I get some error messages like this:
If you are attempting to access a file, make sure it is not ReadOnly.
Make Sure you have sufficient privileges to access this resource.
Get general Help for this exception.
foreach (string subFich in SubFicheiros)
{
listBox.Items.Add("- Deleting File: " + subFich.Substring(Pasta.Length + 1, subFich.Length - Pasta.Length - 1));
ficheirosEncontrador++;
}
try
{
Directory.Delete(Pasta, true);
}
catch (IOException)
{
Thread.Sleep(0);
//The Message Error appears here on this code right below:
Directory.Delete(Pasta, true);
}
catch (UnauthorizedAccessException)
{
Directory.Delete(Pasta, true);
}
}
I would like to get some help with this.
How do i ask the user, to let me get the privilegies to delete it.
Well.. what your code doing is: You're deleting the directory and if it gives any exception then you're again trying to do the same step where you got exception.
First of all error is because files are set to read only or because you dont have enough rights to delete the directory (or probably some process is using the files which you are trying to delete)
foreach (string subFich in SubFicheiros)
{
listBox.Items.Add("- Deleting File: " + subFich.Substring(Pasta.Length + 1, subFich.Length - Pasta.Length - 1));
ficheirosEncontrador++;
}
try
{
var di = new DirectoryInfo(Pasta);
di.Attributes &= ~FileAttributes.ReadOnly;
Directory.Delete(Pasta, true);
}
catch (Exception EE)
{
MessageBox.Show("Error: "+ EE.toString());
}
if this code still doesn't work check if you have admin rights to delete that folder
Sounds like your file is read-only, or you do not have the right to remove the file you want based on your user login.
When we try to search for a user in ActiveDirectory, we get that exception - 0x8007203B.
Basically we deployed a web service, which uses DirectoryEntry & DirectorySearcher class to find a user in AD, and sometimes this exception happens. But when we do IISReset, it again works fine.
Code is very simple like this:
DirectoryEntry domainUser = new DirectoryEntry("LDAP://xxx.yyy/dc=xxx,dc=yyy", "domain\user", "pwd", AuthenticationTypes.Secure);
DirectoryEntry result = new DirectorySearcher(domainUser, filter);
Only some times this happens. I don't have much information to provide, any guess much appreciated
This is how my filter looks like
public static string BuildFilter(DirectoryEntry dirEntry, string userName, string userMail)
{
try
{
string filter = string.Empty;
if (!string.IsNullOrEmpty(userName) && string.IsNullOrEmpty(userMail))
filter = string.Format(#"(&(objectClass=user)(samaccounttype=805306368)(|(CN={0})(samaccountname={0})))", userName);
else if (string.IsNullOrEmpty(userName) && !string.IsNullOrEmpty(userMail))
filter = string.Format(#"(&(objectClass=user)(samaccounttype=805306368)(mail={0}))", userMail);
else
filter = string.Format(#"(&(objectClass=user)(samaccounttype=805306368)(|(CN={0})(samaccountname={0})(mail={1})))", userName, userMail);
return filter;
}
catch (Exception ex)
{
_logger.Error("BuildUserSearch - Failed to build LDAP search", ex);
}
return null;
}
You say that this it's just append after some time. As DirectoryEntry and DirectorySearcher are built on COM object into disposable class I would first just add some using sections to be sure that underlying objects are corectly freed.
using(DirectoryEntry root = new DirectoryEntry(ldapPath))
{
using(DirectorySearcher searcher=new DirectorySearcher(root))
{
...
}
...
}
Any guess are appreciated?
Then here's mine:
ASP.NET: DirectoryServicesCOMException [...];
Windows Error Codes: Repair 0x8007203B. How To Repair 0x8007203B.
What makes me confuse is that you say it works most of the time...
Did this help?
P.S. I'll update if I think of anything else.
I am trying to get the list of local users of a computer using the following code.
internal void GetUsers()
{
try
{
List<string> adUsers = new List<string>();
DirectoryEntry directoryEntry = new DirectoryEntry("WinNT://" + Environment.MachineName);
foreach (DirectoryEntry child in directoryEntry.Children)
{
if (child.SchemaClassName.Equals("User", StringComparison.OrdinalIgnoreCase))
{
adUsers.Add(child.Name);
}
}
}
catch (Exception ex)
{
//Exception
}
}
This code works fine in my computer. However, when I tested it on a few other computers, the following system users were included in the list:
ASPNET,
HelpAssistant
Could some one throw some light on how I can get rid of these system users and get only users who actually log in, ie, normal users.
Thanks,
Ram
Not an answer as such, but some suggestions that might help.
I think the problem is that those accounts aren't real system accounts, so might not be so easy to distinguish.
You could look at the WMI classes Win32_UserAccount and Win32_UserProfile and see if there are any properties in there that might indicate which user accounts are normal ones and which ones are the ones you mention. Specifically, maybe the 'SIDType' or 'AccountType' properties of Win32_UserAccount or maybe the Special property of the Win32_UserProfile class.
Might be other WMI classes that might be worth looking at as well.
Or there might be some way that you can query if a user account has the interactive logon right (which I assume those two accounts might not have normally).
Have you tried enumerating the Properties collection on DirectoryEntry?
using (DirectoryEntry dirEntry = new DirectoryEntry(strchild))
{
foreach (string strPropertyName in dirEntry.Properties.PropertyNames)
{
Console.WriteLine(strPropertyName + " " + dirEntry.Properties[strPropertyName].Value.ToString());
}
}
Other than that, you may have to do an LDAP search on Active Directory to match the UserName you have found to an ActiveDirectory user.
Have a look at this article.
http://www.codeproject.com/KB/system/everythingInAD.aspx
Have fun.
The following code will get you the local users that actually have local accessible folders.
var localDrives = Environment.GetLogicalDrives();
var localUsers = new List<string>();
var query = new SelectQuery("Win32_UserAccount") { Condition = "SIDType = 1 AND AccountType = 512" };
var searcher = new ManagementObjectSearcher(query);
foreach (ManagementObject envVar in searcher.Get())
{
foreach (string drive in localDrives)
{
var dir = Path.Combine(String.Format("{0}Users", drive), envVar["name"].ToString());
if (Directory.Exists(dir))
{
localUsers.Add(envVar["name"].ToString());
}
}
}