Directory.Exists(#"\\SERVERIP\aFolder\bFolder"); always returns false - c#

The following path always returns false:
Directory.Exists(#"\\SERVERIP\aFolder\bFolder");
// where SERVERIP is the server-IP which is being accessed using Impersonation
After debugging the code, it places double-slashes in the Debugger.
I have accessed the above file path without the # and double-quotes in WindowsExplorer.
What am I doing wrong?
[ The code will run on a network ]

The problem might be in the paths-[Source/Destinations] (both or one of it[source/destination] might be causing the problem) due to the default-paths used by Visual-Studio. So let me explain how to check wether the paths are correct/incorrect step by step.
Configuring ** SOURCE-PATH **:
Some times this path DRIVE:\ProgramFiles\IISExpress (or some other path depending on the installation location of IIS) gets concatenated with the SOURCE-PATH you give in the input To solve this problem, follow/verify these steps:
Ensure that the SOURCE-PATH or File you are using is in the Project-Folder
To Access the SOURCE-PATH or File. Always use this path/way:
// 1. SOURCE-PATH + fileName with Extension<br>
Server.MapPath("~\FolderInsideProjectFolder\", "fileName.extension");
Configuring ** DESTINATION-PATH (to a Mapped-NETWORK) **:
This path creates a problem if the path you entered has some words mispelled OR if you don't have access to the specified Server-IP[DestinationServerIP]. To solve this problem, follow/verify these steps:
Before Accessing the DESTINATION-PATH or File , ensure that the IP-Address you are referring to is Accessible to the Account under which your Application-code is running.To learn how to run Applications under an Account. See Impersonization
To Access the DESTINATION-PATH or File. Always use this path/way:
// 2. DESTINATION-PATH + fileName with Extension
#"\\SERVERIP\aFolder\bFolder" + "fileName.extension";
NOTE:
Remember that the SOURCE-PATH can be checked if it (exists/does not exist) by addressing its Fully-Qualified-Address and in that case, it will return true if it exists (The full-path that windows-explorer shows you in the Address Bar (Windows-Explorer) like DRIVE:/....../
EXTRA-INFORMATION: (as it was the basic INTENSION)
One line instruction to Copy the file from local-system → networked-mapped drive/path is:
System.IO.File.Copy(
Server.MapPath("~\FolderInsideProjectFolder\", "fileName.extension"),
#"\\SERVERIP\aFolder\bFolder" + "fileName.extension"
[, true ] // Optional if you want the file to be over-written or not
);
Please inform, if any thing still is not cleared (but after some nice searching ☋ ☛ )

Many a times I have seen file (or directory) access problems when the user (a human, system user such as IIS_IUSR or an application) lacks required privileges.
According to this question where the asker is facing similar problem, I believe that this may help you.
Let us know, if it helps.

Related

Can Directory.Move fail because I am browsing the folder?

I have two folder in a remote FileShare and I am trying to move the first one inside the second. To do this, I wrote a CLR that pretty much does the following:
if (Directory.Exists(destinationFolder))
{
Directory.Delete(destinationFolder, true);
}
if (Directory.Exists(sourceFolder))
{
Directory.Move(sourceFolder, destinationFolder);
}
This works as expected but there are some cases that am getting the following error:
System.IO.IOException: Cannot create a file when that file already exists.
System.IO.IOException: at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath) at System.IO.Directory.InternalMove(String sourceDirName, String destDirName, Boolean checkHost)
I was not able to narrow it down. It seems random to me since I can not reproduced it. I run this code block, over 50 times and I could not get the same error (or any error to tell the truth) as before.
- Do you see anything wrong with code?
- Do you have any "guesses" on what may caused this error?
The only thing I can think, is even though the Directory.Delete(destinationFolder, true); return the system does not delete the directory immediately and thus when Directory.Move(sourceFolder, destinationFolder); runs, the destinationFolder still exists.
(29/12/2016) This is not a duplicate of Cannot create a file when that file already exists when using Directory.Move. There, the user has a 'mistake' in her code and creates (Directory.CreateDirectory(destinationdirectory);) the destination folder. I am not creating the destination folder, nevertheless, I am deleting it if exists. I looked the comments and the answers but none of them gave a solution to my issue.
(30/12/2016) I have tried all the suggestions from the comments and answer but still nothing strange happens. No errors and no unexpected behaviors.
The only thing I can think [of] is even though the Directory.Delete(destinationFolder, true); return the system does not delete the directory immediately and thus when Directory.Move(sourceFolder, destinationFolder); runs, the destinationFolder still exists.
I would highly doubt that this is the cause of any issue. I suppose it is not impossible, especially since this is a folder on another system (remote file share) and not local, but I would still expect any write-behind caching being done on the remote system to be completely transparent to any file system requests, not just some of them.
I think it is more likely, given the code shown in the question, that somehow you initiated two threads at nearly the exact same time and hit a race condition wherein both threads were attempting to process the move operation at the same time. You can both detect such a condition and avoid any errors by making the following changes to your code:
string _LogFile = String.Concat(#"C:\TEMP\SQLCLR_", Guid.NewGuid(), ".log");
File.AppendAllText(_LogFile, #"Starting operation for: " + sourceFolder +
#" --> " + destinationFolder);
if (Directory.Exists(destinationFolder))
{
File.AppendAllText(_LogFile, #"Deleting: " + destinationFolder);
Directory.Delete(destinationFolder, true);
}
if (Directory.Exists(sourceFolder))
{
if (!Directory.Exists(destinationFolder))
{
File.AppendAllText(_LogFile, #"Moving: " + sourceFolder);
Directory.Move(sourceFolder, destinationFolder);
}
else
{
File.AppendAllText(_LogFile, #"Oops. " + destinationFolder +
#" already exists. How odd indeed!");
}
}
This will log the operation to a text file. It will indicate exactly which steps are being taken. It will also check for the existence of the destination before calling "move", something which is not currently being checked.
If there are two competing threads, you will get 2 log files since they are named using a GUID.
If, somehow, it actually is a delayed delete issue on the remote OS, that would be indicated by a single log file containing a line for the "Deleting.." and then one for the "Moving...". OR, if the "exists" check sees the not-yet-deleted destination, then you will see a line for "Oops".
According to MSDN you´ll get that exception in the following cases:
An attempt was made to move a directory to a different volume.
destDirName already exists.
The sourceDirName and destDirName parameters refer to the same file or directory.
The directory or a file within it is being used by another process.
You´ll have to check with some of above cases, there will be the solution for sure.
https://msdn.microsoft.com/en-us/library/system.io.directory.move(v=vs.110).aspx

Removing a directory with files inside AppData

Well, what I want to do is to remove my folder that is located inside Roaming. I want this to work for every user, so the username of every PC is different. I already know that to get path of AppData I need following:
var path = Environment.SpecialFolder.ApplicationData;
But what to do to remove the folder with a specific name (Let's call it ExampleDir)? I tried this:
Path.Combine(path + "Kappa");
Directory.Delete(true.ToString());
But this does not work. I am beginner at C#, still, I want to practice. Will be grateful for help =)
First of all, Path.Combine() is used to replace string concatenation so don't concatenate strings in it. Pass every name you want to concatenate as a parameter and the function will do the rest.
Secondly, to remove a folder containing files you have to use the Directory.Delete(string, bool) overload. The bool value (called recursive) indicates wether you want to remove files and subfolders in the specified directory (see the MSDN Documentation for Directory.Delete()).
And finally, Environment.SpecialFolder.ApplicationData is just an enumration (meaning it's just a number). You have to pass it as a parameter to the Environment.GetFolderPath() method to get the actual path of the AppData folder.
Example:
string AppDataFolder = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
string FolderToDelete = Path.Combine(AppDataFolder, "Kappa");
try
{
Directory.Delete(FolderToDelete, true); //Setting "recursive" to true will remove every subfile/-folder.
}
catch (Exception ex)
{
//An error occurred, use this block to log it/show it to the user/whatever.
//ex.Message - The error message.
//ex.StackTrace - Where in the code the error occurred.
}
EDIT:
As #dman2306 said in his comment, some exception handling is good practice in case of that the deletion fails. I have added this to my above code.
The code in the try block will run until an exception is thrown (if any). If an exception is thrown the execution will move on to the catch block, which is where you catch the exception and perform for example error logging, stopping other procedures, etc.
EDIT 2:
You possibly have to add "Roaming" to Path.Combine(). I am unsure if it's already included or not, and I'm unable to test that now.
string FolderToDelete = Path.Combine(AppDataFolder, "Roaming", "Kappa");
Forget what I said, SpecialFolder.ApplicationData gives you the path to the Roaming folder.
First of all you are using Path.Combine() wrong. But you don't need that at all.
Second you have to use backslases to separate folders in a path when combining them with +.
And third: The method Directory.Delete() wants the path of the folder you want to delete as an argument.
Try this:
Directory.Delete(Environment.SpecialFolder.ApplicationData + "\\Kappa");

Could trying to copy a file owned by another process cause a DirectoryNotFoundException?

The log I'm trying to work with belongs to another program that runs concurrently with my own. I get a DirectoryNotFoundException stating "Could not find a part of the path " when I try to make the copy. The assert does pass. The exception is thrown at File.Copy(...) itself. With the if(File.Exists(...)) in place, the program is clearly able to see the file before it attempts to copy it.
Edit: Could permissions be a possible cause? The directory is located in the root of the C drive.
Edit: By adding the two asserts suggested by Jim Mischel and stepping through in the cold light of a new day, newControlProgramLog path was revealed as the culprit. GetSaveFilePath() was returning a default path for the particular run state I was testing. I declared the default but never checked to see that it existed on program start up. The directory is now created if it does not exist, and the function now works as intended.
Shout out to Christian Hagelid for calling that it wasn't an issue with controlProgramLogPath from the start.
private void CopyLogsToDataDirectoy()
{
Debug.Assert(Directory.Exists(_controlProgramDirectory));
string controlProgramLogPath = Path.Combine(_controlProgramDirectory, _controlProgramLogFileName);
if (File.Exists(controlProgramLogPath))
{
string dataFilePath = GetSaveFilePath();
string newControlProgramLogName = Path.GetFileNameWithoutExtension(dataFilePath);
newControlProgramLogName = newControlProgramLogName + ".control.log";
string newControlProgramLogPath = Path.GetDirectoryName(dataFilePath);
newControlProgramLogPath = Path.Combine(newControlProgramLogPath, newControlProgramLogName);
File.Copy(controlProgramLogPath, newControlProgramLogPath);
}
}
DirectoryNotFoundException occurs when part of the path you specified does not exist. It does not occur because a file is locked. If you get DirectoryNotFoundException, then it's almost certainly because the string you supplied does not reference a valid directory path. Documentation also says that you can get this exception if your code doesn't have the PathDiscovery permission. I suspect that's pretty unlikely in your case.
You should check the paths in controlProgramLogPath and newControlProgramLogPath immediately before calling File.Copy.
Debug.Assert(Directory.Exists(Path.GetDirectoryName(controlProgramLogPath));
Debug.Assert(Directory.Exists(Path.GetDirectoryName(newControlProgramLogPath));
I suspect that will reveal the problem.

Viewing Properties.Settings.Default variables

I am trying to use Settings.settings to define/persist some vars. For brevity, I've set up a test file to demonstrate the behavior I'm seeing:
First, I define a setting in Settings.settings:
I then have the following code to test changing variableName:
public Form1()
{
InitializeComponent();
string newString = Properties.Settings.Default.variableName;
Properties.Settings.Default.variableName = "This is a new string";
Properties.Settings.Default.Save();
}
Running the above in the debugger for the first time, I grab the current value (the value I set in the Settings.settings window initially) of variableName from Properties.Settings. As expected, newString is set to "This is a string". Good.....
After executing the next two lines, the debugger shows variableName changed to "This is a new string". Good....
I then run the app through the debugger again. I hit the string newString line and, prior to execution, newString is undefined (of course). Good....
As soon as I execute...
string newString = Properties.Settings.Default.variableName;
... and on subsequent executions of the code, the actual value of variableName is defined as "This is a new string" (Good...as expected).
I then go back to the Settings.settings window. variableName has not changed - it's still "This is a string". I've even closed VSE 2012 and re-opened the project. Settings.settings never changes.
Where is the new value being stored? I've checked all of the .config files ([appname].exe.config, [appname].vshost.exe.config, app.config, and the Settings.settings file) and the new value, "This is a new string" isn't anywhere to be found.
In summary, I'm getting the result I desire from the code, but I can't seem to view the result at design time other than to check the value of the var in the debugger. This seems not only peculiar to me, but impossible.
What am I missing/where am I not looking? I would fully expect the value of variableName to change in the Settings.settings window, but it never does. I've looked everywhere on StackOverflow/Google and can't seem to find the answer.
Thanks in advance....
The original value that you configured via Settings.settings is stored in a .config file alongside your executable's assembly. This will never change unless you modify the Settings file directly via Visual Studio; it's essentially a read-only file.
The user's customized setting is stored in a separate config file within the user's profile. The location of this file depends on your assembly's metadata. For example, on Windows 7/Vista the location might look like:
C:\Users\<user name>\AppData\Local\<company name>\<assembly name>\
AssemblyName\<version>\user.config
If you haven't customized the company name in your assembly's metadata then it may default to Microsoft. Also note that AppData is a hidden folder that may not be visible in Windows Explorer depending on your view settings.
I am not sure if I understand your question. That variable content stay persistent. Thats it. Why you would set a persistent variable to change it later?

Assembly.GetExecutingAssembly().Location returns the "wrong" value

I try to use the code below on Monodroid, but "path" is always an empty string.
The interesting thing is that it has already worked, and I don't know what has changed.
The "writeline" below is just for testing purposes, it produces: ": MyDLL.dll: : ".
Last week I updated to mono-android-4.2.7.15330979, but it also worked there.
string path = System.IO.Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
System.Console.WriteLine("{0}: {1}: {2}: {3}", path, Assembly.GetExecutingAssembly().Location, System.IO.Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), Path.GetDirectoryName(Assembly.GetAssembly(GetType()).Location));
Did I make a mistake?
Is there any known problem with this Assembly functions in mono-android?
EDIT : I also tried this command in std c# in a console application, there it worked!
I found out that the command works, if the project option "Use Fast Deployment(debug mode only)" is enabled. Could this become a problem, when the app is distributed, or built as release?

Categories