Error : System.IO.IOException: the network path was not found - c#

when i am executing following code it results an error please help me to resolve this.
class MySample
{
public static void Main()
{
string eventLogName = "Security";
string sourceName = "BTHUSB";
string machineName = "v.i.com";
EventLog eventLog;
eventLog = new EventLog();
eventLog.Log = eventLogName;
eventLog.Source = sourceName;
eventLog.MachineName = machineName;
foreach (EventLogEntry log in eventLog.Entries.Cast<EventLogEntry>().Reverse())// Entries.Cast<EventLogEntry>().Reverse
{
Console.WriteLine(") Entry type: {0} , Category: {1}, Data: {2}, ID: {3}, Source: {4} \n", log.EntryType, log.TimeWritten, log.EventID, log.InstanceId, log.Source);
}
}
}
Error is ,
Unhandled Exception: System.IO.IOException: The network path was not found.
at Microsoft.Win32.RegistryKey.Win32ErrorStatic(Int32 errorCode, String str)
at Microsoft.Win32.RegistryKey.OpenRemoteBaseKey(RegistryHive hKey, String ma chineName)
at System.Diagnostics.EventLog.GetEventLogRegKey(String machine, Boolean writ able)
at System.Diagnostics.EventLog.Exists(String logName, String machineName)
at System.Diagnostics.EventLog.OpenForRead(String currentMachineName)
at System.Diagnostics.EventLog.GetEntryAtNoThrow(Int32 index)
at System.Diagnostics.EventLogEntryCollection.EntriesEnumerator.MoveNext()
at System.Linq.Enumerable.<CastIterator>d__aa`1.MoveNext()
at System.Linq.Buffer`1..ctor(IEnumerable`1 source) at System.Linq.Enumerable.<ReverseIterator>d__99`1.MoveNext()
at event.MySample.Main() in E:\.net prep\.net examples\event\event\Program.cs :line 42
please help me to resolve this, in a machine name field how to enter the remote machine, when it have v.i.com , but that system name is v only.

If you look at your stack trace you can see the failure happens trying to open the remote registry key.
This means that the Remote Registry service is not running on the target machine. On v.i.com, open the services control panel (services.msc) and start the service called Remote Registry.
This service is normally set to have the startup type of Manual so is not started automatically. If you need to configure or access the event log remotely often, set this to start Automatic so that it's always available.

I'd assume the machineName "Venus.InsTIL.com" which you've specified is not contactable via this path. What's the UNC path to the machine? Have you verified the machine is otherwise contactable (ping, UNC file browse etc)?

What account is that code running with? It may not have permission to access the network. That will depend on the web service configuration.
Something else is that recent OS versions do not allow strictly local accounts to access administrative shares on other systems, and that will be the account again.

It is likely that you did connect to the other machine. I would expect that the error would be more like connection refused or invalid credentials if the connection failed. The fact that this exception is happening on a move next operation (see stack trace) implies that the code was reading through the list when it attempted to read an entry that was not there. My guess is that the entry had been there when the foreach command created its list, but not there when iterating through the list. I suspect the issue is that something is changing the data on you.

Related

NullPointerException with MR2 in windows

I have installed Hadoop 2.3.0 in windows and able to execute MR jobs successfully. But while trying with streaming sample in C# [with HadoopSDK's .Net assemblies] the app ends with the following exception
14/05/16 18:21:06 INFO mapreduce.Job: Task Id : attempt_1400239892040_0003_r_000000_0, Status : FAILED
Error: java.lang.NullPointerException
at org.apache.hadoop.mapred.Task.getFsStatistics(Task.java:347)
at org.apache.hadoop.mapred.ReduceTask$OldTrackingRecordWriter.<init>(ReduceTask.java:478)
at org.apache.hadoop.mapred.ReduceTask.runOldReducer(ReduceTask.java:414)
at org.apache.hadoop.mapred.ReduceTask.run(ReduceTask.java:392)
at org.apache.hadoop.mapred.YarnChild$2.run(YarnChild.java:168)
at java.security.AccessController.doPrivileged(Native Method)
at javax.security.auth.Subject.doAs(Subject.java:415)
at org.apache.hadoop.security.UserGroupInformation.doAs(UserGroupInformation.java:1548)
at org.apache.hadoop.mapred.YarnChild.main(YarnChild.java:163)
Update:
I was able to drill down the problem and found that the exception raised in the following line
matchedStats = getFsStatistics(FileOutputFormat.getOutputPath(job), job);
at org.apache.hadoop.mapred.ReduceTask$OldTrackingRecordWriter.<init>(ReduceTask.java:478)
In the above, the result of 'FileOutputFormat.getOutputPath(job)' returns null, which throws the null pointer exception. Below are the codes for the getOutputPath() function.
public static final String OUTDIR = "mapreduce.output.fileoutputformat.outputdir";
public static Path getOutputPath(JobConf conf) {
String name = conf.get(org.apache.hadoop.mapreduce.lib.output.
FileOutputFormat.OUTDIR);
return name == null ? null: new Path(name);
}
So Is it needed to set value for property "mapreduce.output.fileoutputformat.outputdir" anywhere in the configuration files to get this issue resolved?
Thanks
The problem is that the hadoop services have been started from a different user [SYSTEM in my case] and the mapreduce sample was submitted from my local user. So this makes the issue by returning the FileSystem statistics [for the local user] as Null.
Once i started Hadoop from my local user, the above issue gets resolved.

Azman gives same error using either local xml or SQL Server for storage

Recently two users in our system started getting this error when trying to add them to a role.
System.Runtime.InteropServices.COMException: Cannot create a file when that file already exists. (Exception from HRESULT: 0x800700B7)
What is interesting is that the same error occurs regardless of the configuration, running locally we use an XML store and in the test environment it uses SQL Server.
Here is code where is blows up - AddMemberName() - as you can see this is pretty straightforward stuff and it's worked well for a while, it's just these two users all of the sudden
public void AddUserToRole(string roleName, string userName, bool upn)
{
string uName = userName;
if (upn)
uName = getAltUserNames(userName).First();
AzAuthorizationStore store = new AzAuthorizationStoreClass();
store.Initialize(2, _provider.StoreLocation, null);
IAzApplication app = store.OpenApplication(_provider.ApplicationName, null);
IAzRole role = app.OpenRole(roleName, null);
role.AddMemberName(uName, null);
role.Submit(0, null);
Marshal.FinalReleaseComObject(role);
}
I tried googling various different terms but can't find much of anything regarding this. I did read this post but it doesn't seem to be the issue.
Thanks
Check you Active Directory usernames and the underlying OU name especially. Check for duplicates and mismatches.
I had an issue once where a user got married and her name changed.

FtpWebRequest WebException: "Unable to connect to the remote server"

I have code in a Windows Service that successfully connects to an FTP server when I run it locally through a test harness (with the FTP server being on another machine on the local network).
When I install it in the production hosting environment, though, I get the dreaded WebException "Unable to connect to the remote server". It doesn't seem to matter whether I'm using ACTV or PASV FTP, all I get it this WebException. If I try to FTP from the Windows command line, however, it works perfectly well (so it's not the firewall at fault).
The code I'm using (adapted from How to List Directory Contents with FTP in C#?) reads:
private static readonly string __ftpSourceServer = "ftp://"
+ ConfigurationManager.AppSettings["FtpServer"] + "/";
private static readonly NetworkCredential __ftpCreds = new NetworkCredential(
ConfigurationManager.AppSettings["Username"],
ConfigurationManager.AppSettings["Password"]);
// And now the method MediaSyncDaemon.GetFilesToFetch:
bool usePassive = Boolean.TryParse(ConfigurationManager.AppSettings["UsePassive"]
, out usePassive) && usePassive;
Uri ftpSrv = new Uri(__ftpSourceServer + Uri.EscapeUriString(
ConfigurationManager.AppSettings["FtpPath"]));
Logger.Debug("Connecting to FTP server at " + ftpSrv + "; PASV? " + usePassive);
FtpWebRequest listRequest = (FtpWebRequest) WebRequest.Create(ftpSrv);
listRequest.Method = WebRequestMethods.Ftp.ListDirectory;
listRequest.Credentials = __ftpCreds;
listRequest.UsePassive = usePassive;
listRequest.UseBinary = false;
using (FtpWebResponse listResponse = (FtpWebResponse) listRequest.GetResponse())
{
// ReSharper disable AssignNullToNotNullAttribute
return new StreamReader(listResponse.GetResponseStream())
.ReadToEnd().Split(new[] { '\n', '\r' },
StringSplitOptions.RemoveEmptyEntries)
.Where(s => s.EndsWith(".zip", true, CultureInfo.InvariantCulture))
.ToList();
// ReSharper restore AssignNullToNotNullAttribute
}
The exception is thrown at the FtpWebRequest.GetResponse() call in the using line (outside the return statement), with nothing else in the stack trace:
System.Net.WebException: Unable to connect to the remote server
   at System.Net.FtpWebRequest.GetResponse()
   at (that line number in that file)
The only real difference between my test harness (which works) and the production environment (which doesn't) is the presence of a firewall in the production environment — all four servers are on slightly different subnets:
Dev client 10.16.6.155 subnet 255.255.255.128
Dev server 10.16.7.242 subnet 255.255.255.0
Prod client 192.168.102.107 subnet 255.255.255.0
Prod server 192.168.203.110 subnet 255.255.255.0
but the firewall can't be the problem is I can FTP from Prod client to Prod server interactively, just not programmatically.
I've tried changing the bool appSettings value for UsePassive and that makes no difference and, in every case, nothing shows up in the FTP server log (so it's not getting that far).
Now I'm not expecting anyone to be able to debug the hardware infrastructure of my hosting environment, but I'm struggling to think of what else I could vary to get this to work. I've seen it work locally in my test harness, calling the same method. In case it helps, the test harness code reads as follows:
[NUnit.Framework.Test]
public void FtpFileListTest()
{
ICollection<string> files = MediaSyncDaemon.GetFilesToFetch();
Assert.IsNotNull(files);
Assert.Greater(files.Count, 0);
}
Does anyone have any ideas of what else I could try, please?
Thanks!
Update
Having had some suggestions of places to look in the comments, I can update this a little further:
The problem does not appear to be user permissions — the service is running in the context of the Local System account (which has more permissions than Administrator does)
The problem does not appear to be code-access security. I've added a SocketPermission.Demand call to the entry method for this chunk of code:
System.Security.CodeAccessPermission socketPermission;
socketPermission = new SocketPermission(NetworkAccess.Connect,
TransportType.Tcp, ConfigurationManager.AppSettings["FtpServer"], 20);
socketPermission.Demand();
socketPermission = new SocketPermission(NetworkAccess.Connect,
TransportType.Tcp, ConfigurationManager.AppSettings["FtpServer"], 21);
socketPermission.Demand();
And I'm not seeing any SecurityException being thrown as a result; I'm still getting the same WebException, at the new line number for that same code position.
Does anyone have any further suggestions of what I could try?
I would like to share our problem and solution:
We were not able to connect to the FTP server with ftpwebrequest on a corporative PC, but on ours it would work fine.
The issue was that ftpwebrequest() was grabbing the proxy configuration that the company’s IT forces on the PC.
To resolve this issue, we added (ftpwebrequest object).proxy = null; before connecting.

How does one lookup the error number in Windows EventLogEntry Message

I am trying to read through the Windows Event log "Error" entry messages in in c#.
foreach (EventLogEntry log in eventLog.Entries)
{
if (log.EntryType.ToString() == "Error")
{
Console.WriteLine( log.Message);
}
}
The output is "The XYZ service failed to start due to the following error: \r\n%%2"
while the entry I am looking for is
"The XYZ service failed to start due to the following error:\r\nThe system cannot find the file specified."
How does one translate from the id to the appropriate error message ?
Many thanks,
KG
Event log messages are templates, something like:
The %1 service failed to start due to the following error: \r\n%2
An event log entry contains a message number and replacement strings to substitute for %1, %2, etc.
The .Net EventLogEntry.Message property does the substitution for you, so you should never see the %1, %2, etc.
It looks like the substitution is failing, perhaps because there aren't enough replacement strings (check the EventLogEntry.ReplacementStrings property) or the format string is malformed (it seems to have a stray '%'). Though neither of these explanations seem plausible if the log entry is coming from the Service Control Manager.

Directory.CreateDirectory access to path is denied?

I have server-client application, it's a file manager
my problem is when I go inside a folder which requires access control like system folders, it becomes to read-only, but I need to move/delete or create new folder, how can I get the permission to do that?
here's how I create a new folder at the server side
public void NewFolder(string path)
{
try
{
string name = #"\New Folder";
string current = name;
int i = 0;
while (Directory.Exists(path + current))
{
i++;
current = String.Format("{0} {1}", name, i);
}
Directory.CreateDirectory(path + current);
Explore(path); //this line is to refresh the items in the client side after creating the new folder
}
catch (Exception e)
{
sendInfo(e.Message, "error");
}
}
There are often directories on a drive that even a user with administrator privileges cannot access. A directory with a name like "HDDRecovery" is quite likely to be troublesome like this. Surely it contains sensitive data that helps the user recover from disk failure. Another directory that fits this category is "c:\system volume information", it contains restore point data.
An admin can change the permissions on folders like this. But of course that doesn't solve the real problem nor is it a wise thing to do. Your user can't and shouldn't. Be sure to write code that deals with permission problems like this, simply catch the IOExeption. Keep the user out of trouble by never showing a directory that has the Hidden or System attribute set. They are the "don't mess with me" attributes.
If you want to remove directory read-only attribute use this: http://social.msdn.microsoft.com/Forums/en/vblanguage/thread/cb75ea00-f9c1-41e5-ac8e-296c302827a4
If you want to access system folders you can run your program as local administrator.
I had a similar problem (asp.net MVC vs2017) with this code:
Directory.CreateDirectory("~/temp");
Here is my solution:
// Create path on your web server
System.IO.Directory.CreateDirectory(System.Web.HttpContext.Current.Server.MapPath("~/temp"));
I also ran into an issue similar to this, but I was able to manually navigate through Windows Explorer and create directories.
However, my web app, running in VS on my laptop, hosted through my local IIS and not the built-in IIS deal for VS, was triggering the Access Denied issue.
So when I was hitting the error in code, I drilled down to glean more data from the System.Environment object and found the user, which of course was the App Pool that my app was running under in IIS.
So I opened IIS and opened the Advanced Settings for the app pool in question and changed the Identity to run under Network Service. Click OK. "cmd -> iisreset" for good measure. Try the app again, and SUCCESS!!!!
I had the same issue when creating a directory. I used DirectorySecurity as shown below:
DirectorySecurity securityRules = new DirectorySecurity();
securityRules.AddAccessRule(new FileSystemAccessRule(#"Domain\AdminAccount1", FileSystemRights.Read, AccessControlType.Allow));
securityRules.AddAccessRule(new FileSystemAccessRule(#"Domain\YourAppAllowedGroup", FileSystemRights.FullControl, AccessControlType.Allow));
DirectoryInfo di = Directory.CreateDirectory(path + current, securityRules);
Also keep in mind about the security as explained by Hans Passant's answer.
Full details can be found on MSDN.
So the complete code:
public void NewFolder(string path)
{
try
{
string name = #"\New Folder";
string current = name;
int i = 0;
while (Directory.Exists(path + current))
{
i++;
current = String.Format("{0} {1}", name, i);
}
//Directory.CreateDirectory(path + current);
DirectorySecurity securityRules = new DirectorySecurity();
securityRules.AddAccessRule(new FileSystemAccessRule(#"Domain\AdminAccount1", FileSystemRights.Read, AccessControlType.Allow));
securityRules.AddAccessRule(new FileSystemAccessRule(#"Domain\YourAppAllowedGroup", FileSystemRights.FullControl, AccessControlType.Allow));
DirectoryInfo di = Directory.CreateDirectory(path + current, securityRules);
Explore(path); //this line is to refresh the items in the client side after creating the new folder
}
catch (Exception e)
{
sendInfo(e.Message, "error");
}
}
My suspicion is that when you are running the application in client/server mode, the server portion needs to be running as Administrator, in addition to possibly removing read-only or system flags, to be able to do what you want.
That said, I agree with #HansPassant- it sounds like what you are trying to do is ill-advised.
Solved:
Directory created on remote server using below code & setting.
Share folder and give the full permission rights also in Advance
setting in the folder.
DirectoryInfo di = Directory.CreateDirectory(#"\\191.168.01.01\Test\Test1");
Test is destination folder where to create new Test1 folder(directory)

Categories