Unable to delete a desktop folder - c#

Problem: I am unable to delete a folder (including contents) within a
desktop folder programatically with C#. If I copy the value of
desktopDestinationPath and paste it into Windows Explorer, I can open
this folder (conclusion, the path is valid) The test -
Directory.Exists(desktopDestinationPath) - returns as true and I drop
into the code block (conclusion, the path is valid)
Directory.Delete(desktopDestinationPath, true) - throws exception
(conclusion, path no longer valid) If I copy the path value from the
exception and paste it into Windows Explorer, I can open this folder
(conclusion, the path is valid)
What I have tried: Build, Rebuild, Clean Solution, restart visual
studio. Also, If I delete the folder manually and run the code, the
folder is successfully built. However, when I run a second time, I get
the exception. Result: Puzzled look and this post. Sorry if I put
too much detail. I am open to help with a solution and criticism on
how I posted (both will help me learn) Thanks in advance! Visual
Studio Info is toward the bottom of this entry. I am using: Microsoft
Visual Studio Premium 2013 (C#).
My code:
// preceded by other code in the method
if (Directory.Exists(desktopDestinationPath)) // desktopDestinationPath is "C:\\Users\<me>\\Desktop\\<folder 1>\\<folder 2>"
{
Directory.Delete(desktopDestinationPath, true); // exception is thrown here <***> "C:\\Users\\<me>\\Desktop\\<folder 1>\\<folder 2>"
// create folder
Directory.CreateDirectory(desktopDestinationPath);
// Call a method to perform Xcopy
ProcessXcopy(SourceLoc, desktopDestinationPath);
}
// followed by an else which creates folder if it does not exist
My code is throwing the following exception: // NOTE I am using Pri.Longpath
System.IO.DirectoryNotFoundException was unhandled by user code HResult=-2147024893 Message=Could not find a part of the path 'C:\Users\ljones\Desktop\folder 1\folder2\fldr3\fldr4\fldr5\fldr6\fldr7\fldr8\fldr9'. Source=mscorlib StackTrace: at System.IO.Directory.DeleteHelper(String fullPath, String userPath, Boolean recursive, Boolean throwOnTopLevelDirectoryNotFound) at System.IO.Directory.Delete(String fullPath, String userPath, Boolean recursive, Boolean checkHost) at System.IO.Directory.Delete(String path, Boolean recursive) at UnitTests.GatMinerTest.CreateDesktopDestinationFolder(String desktopPath) in c:\Users\some folder\Source\Workspaces\some folder\some folder\some folder\some file:line 93 at UnitTests.GatMinerTest.IcwIntegrationMethod() in c:\Users\some folder\Source\Workspaces\some folder\some folder\some folder\some file:line 65 InnerException:
From the web I have learned: A DirectoryNotFoundException exception
is thrown when part of a file path or a directory is not found. Verify
that the directory appears in the specified location. Check that the
directory exists in the specified location. // I am fairly (99.9%)
certain the directory exists When using relative paths, make sure the
current directory is correct. The path may be incorrect if you are
assuming an incorrect current directory. // I am fairly (99.9%)
certain the directory exists

Thank you all for your help in finding an answer. Specifically, thanks for the tips on posting a question in a more appropriate manner.
The solution was an error on my part (go figure).
In code that I did not disclose, there is a call to xcopy. I believe during testing, I had ran past that point and xcopy was working in the background (still had its hooks into my folder structure). Therefore, I couldn't delete it.
My apologies if I wasted your time. Your nudges helped push me toward finding the error in my ways.
Thanks again!

Related

UnauthorizedAccessException in UWP Directory.CreateDirectory

This is a Unity project building to Hololens 2. I'm trying to create a new folder within the Application.PersistentDataPath but it's failing due to UnauthorizedAccessException. Strange thing is it's been working and only recently with seemingly unrelated changes it stopped.
Here's the function that is failing.
static DirectoryInfo EnsureDirectory(string subFolder)
{
Debug.Log($"starting EnsureDirectory() for {subFolder}.");
string directoryPath = Path.Combine(Application.persistentDataPath, subFolder.ValidatePath());
Debug.Log($"About to create directory {directoryPath}");
var dir = Directory.CreateDirectory(directoryPath);
Debug.Log($"Successfully created directory {dir.FullName}");
return dir;
}
At Directory.CreateDirectory I get the error as follows:
Hololens screenshot of debug log
EXCEPTION: UnauthorizedAccessException: Access to the path "C:\" is denied.
This error only happens when deployed to the device. In the Unity editor it works perfectly. I also don't know why it would say "C:" when that's not the path I'm trying to use.
Any help would be greatly appreciate.
Thank you #aybe for the answer that did the job.
This is probably because it checks for every path segment, starting
with the first one which is root and obviously forbidden. Try new
DirectoryInfo(Application.persistentDataPath).CreateSubdirectory(...);
instead to see if the error vanishes

Publishing an Azure function returns "Publish has encountered an error" path \bin does not exist

I'm trying to publish my first test function to Azure functions. When I publish I get the error:
Publish has encountered an error.
Publish has encountered an error. We were unable to determine the cause of the error. Check the output log for more details.
A diagnostic log has been written to the following location:
"C:\Users\me\AppData\Local\Temp\tmp2C29.tmp"
The contest of that file say it was an unknown error, check the output log.
When I look at my output window I see this:
2>Unhandled Exception: System.IO.DirectoryNotFoundException: The path `D:\Dev\FunctionsTest-master\custom-binding\obj\Debug\netstandard2.0\PubTmp\Out\bin` does not exist. Unable to generate Azure Functions extensions metadata file.
2> at ExtensionsMetadataGenerator.ExtensionsMetadataGenerator.Generate(String sourcePath, String outputPath, Action`1 logger) in D:\src\gh.fabiocav\azure-functions-host\tools\ExtensionsMetadataGenerator\src\ExtensionsMetadataGenerator.Console\ExtensionsMetadataGenerator.cs:line 25
2> at ExtensionsMetadataGenerator.Console.Program.Main(String[] args) in D:\src\gh.fabiocav\azure-functions-host\tools\ExtensionsMetadataGenerator\src\ExtensionsMetadataGenerator.Console\Program.cs:line 28
2>Metadata generation failed.
I looked and the ...\PubTmp\Out\bin folder is not where it's being compiled. The actual folder is \PubTmp\Out\ (one folder higher).
I don't see any way of changing the folder location, I tried under properties of the function - build, but that path is the top level; not the final path.
I also don't see any way of selecting where the publish is looking for the compiled functions to publish.
How do I get these locations to be the same for the publish to work?
It appears that this was a bug in Visual Studio 2019. Patching to the current version took care of it.

SharpZipLib - IO Exception while unzipping file

I am using SharpZipLib in my application to Unzip files. I have a folder in which the zip is copied and is extracted there itself. ZIP and Folder name is a guid.
Folder mostly contains 1 or 2 XML files of size 45kb on an average.
Following is the SAN storage where we store all the files (its not exact):
\\sharableFolder\Folder1\Folder2\Folder3
Few days ago errors were logged.
The following error was logged continuously whenever unzip operation was performed:
An attempt was made to create more links on a file than the file system supports
We googled about this issue and we found following links:
https://msdn.microsoft.com/en-us/library/cc231199.aspx
https://msdn.microsoft.com/en-us/library/windows/desktop/ms681383
But we did not find help to resolve it.
We checked:
Limit of files and folders a Folder can contain
For FAT : Maximum number of files in a single folder: 65,534
For NTFS : Maximum number of files in a single folder: 4,294,967,295
We assumed that there is an issue with the no of ZIP files. Currently there are total 1,31,760 files (Zip and Folders) present. We created 1,00,000 ZIP files and also extracted same no of files using ICSharpZipLib. So in total there were 2,00,000 files in a folder. Our assumption that a folder can not contains 1,31,760 files was failed.
We tried alternate code to unzip file. That also didn't work.
We checked for path whether its too long. But that is also not the case.Path was in limit.
We tried moving out few thousand files. But this solution even didn't work.
Lastly we created a new folder and updated the path with the new folder. It worked properly.
But I want to know what could be the cause of this issue. This may happen with other folder on Production.
Any help is appreciated. Thanks in advance
Following is stack trace:
type="System.IO.IOException"
message="An attempt was made to create more links on a file than the file system supports."
source="mscorlib"
detail="System.Exception
System.IO.IOException: An attempt was made to create more links on a file than the file system supports.
at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
at System.IO.Directory.InternalCreateDirectory(String fullPath, String path, Object dirSecurityObj, Boolean checkHost)
at System.IO.Directory.InternalCreateDirectoryHelper(String path, Boolean checkHost)
at ICSharpCode.SharpZipLib.Zip.FastZip.ExtractEntry(ZipEntry entry)
at ICSharpCode.SharpZipLib.Zip.FastZip.ExtractZip(Stream inputStream, String targetDirectory, Overwrite overwrite, ConfirmOverwriteDelegate confirmDelegate, String fileFilter, String directoryFilter, Boolean restoreDateTime, Boolean isStreamOwner)
at ICSharpCode.SharpZipLib.Zip.FastZip.ExtractZip(String zipFileName, String targetDirectory, Overwrite overwrite, ConfirmOverwriteDelegate confirmDelegate, String fileFilter, String directoryFilter, Boolean restoreDateTime)
at MyProject.ProjectFile.File.UnzipFile(String ErrorFile, String& ErrorXMLPath, String& FEXMLPath, String mXMLPath)
at MyProject.ProjectFile.File.ValidateUnzippedFile(Object items)
--- End of inner exception stack trace ---

How to include libsodium.net on ASP.NET

I have an old webservice build on ASP.NET (using .asmx) files. I need to use sodium.net - unfortunately it fails while loading the dependent libsodium.dll file. Any ideas about what I make wrong?
I have added libsodium.net through NuGet.
I have renamed the 64 bit DLL to "libsodium.dll" (and other naming conventions too).
I have tried to reference libsodium.dll directly but VS rejects it (not a valid DLL). So I have added it as "content" instead with "copy to output".
After building I can see that the website/Bin folder contains both sodium.dll (the .NET assembly) and libsodium.net.
When I try to use libsodium.net I get:
ERROR 2015-02-02 11:14:27,118 13798ms [41] CabinetService doRequest - Caught: The type initializer for 'Sodium.SodiumCore' threw an exception.
System.TypeInitializationException: The type initializer for 'Sodium.SodiumCore' threw an exception. ---> System.DllNotFoundException: Unable to load DLL 'libsodium.dll': The specified module could not be found. (Exception from HRESULT: 0x8007007E)
at DynamicDllInvokeType.sodium_init()
at Sodium.SodiumCore..cctor()
--- End of inner exception stack trace ---
at Sodium.SodiumCore.LibraryName()
at Sodium.SecretBox.Create(Byte[] message, Byte[] nonce, Byte[] key)
at Macaroons.SecretBoxCryptoAlgorithm.Encrypt(Byte[] key, Byte[] plainText) in c:\Projects\Macaroons.Net\Macaroons.Net\SecretBoxCryptoAlgorithm.cs:line 58
So it cannot find "libsodium.dll" even though it is in the Bin folder. I did also try to remove the dependency on "sodium.net" where after I got a runtime error saying "sodium.net" is missing - when I re-added it, that error disappeared and I got the one above instead (indicating the "sodium.net" loads correctly).
So I open up the website shadow folder in "C:\Windows\Microsoft.NET\Framework\v4.0.30319\Temporary ASP.NET Files\cabinetservice" and search for "sodium". The only result is "sodium.dll" in some subfolder. There is no "libsodium.dll".
So apparently ASP.NET ignores the "libsodium.dll" file when creating the shadow copy of the website.
I have also tried adding the libsodium.dll (32 bit) to C:\Windows\System32 and libsodium.dll (64 bit) to C:\Windows\SysWOW64. Same result.
And I have tried C:\Windows\Microsoft.NET\assembly\GAC_32\libsodium and C:\Windows\Microsoft.NET\assembly\GAC_64\libsodium. Same result.
How can I make ASP.NET aware of the dependency?
It turns out that ASP.NET doesn't make shadow copies of unmanaged DLLs such as libsodium.dll and libsodium-64.dll.
Sodium.dll (the managed code) tries to load the DLLs from either the same directory as the shadow copy of Sodium.dll (which is not going to work) - or some where in the PATH environment variable's directories.
My solution was to add the AppDomain \Bin directory to the path before calling any Sodium code:
// Make it possible to load unmanaged libsodium DLLs that .NET does not make shadow copies of.
// -> Simply point the "path" variable to the Bin directory.
string path = Environment.GetEnvironmentVariable("PATH");
string binDir = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Bin");
Environment.SetEnvironmentVariable("PATH", path + ";" + binDir);
Update January 2018 (from Jordan Rieger's answer):
Note that you may also need to install the Microsoft Visual C++ 2015
Redistributable on your server (either the x64 or x86 target,
depending on your process.)
Don't forget to restart your app pool (I did an IIS reset) after
installing the redistributable.
Note that you may also need to install the Microsoft Visual C++ 2015 Redistributable on your server (either the x64 or x86 target, depending on your process.)
Don't forget to restart your app pool (I did an IIS reset) after installing the redistributable.
See my comment on https://stackoverflow.com/a/45078280/284704.

WmAutoUpdate - anyone used it? Won't roll back

I've built a Compact Framework application and I'm using WmAutoUpdate to deploy new versions to the mobile devices (http://www.sebastianvogelsang.com/2009/09/23/wmautoupdate-a-net-compact-framework-auto-update-library/). Has anyone used this? It's cool but I've got a problem.
If I cause the application to crash half-way through updating it is supposed to recover by copying the backup version back into the main directory. This doesn't work because the exe file is "locked" by the operating system because it is currently in use. I can verify this is the case because I can't delete it using Windows Explorer either. The error details are:
System.IO.IOException was unhandled
Message="IOException"
StackTrace:
at System.IO.__Error.WinIOError(Int32 errorCode, String str)
at System.IO.File.Move(String sourceFileName, String destFileName)
at WmAutoUpdate.Updater.assertPreviousUpdate()
at WmAutoUpdate.Updater..ctor(String url)
The error occurs on this line in Updater.assertPreviousUpdate():
File.Move(f, appPath + "\\" + getFilenameFromPath(f));
The code manages to update the application exe file when it's allowed to run normally (I'm not sure how). The problem is that it doesn't work when rolling back.
Cheer
Mark
I've used WmAutoUpdate and I've found the same problem. The issue is that you can move the files of the actual running process, but you cannot overwrite them. If you check the update part, WmAutoUpdate moves the running application to a backup directory and then it writes the update version to the original directory. I have fixed the rollback part this way:
if (Directory.Exists(backupDir))
{
string tmpDir = Path.Combine(Path.GetTempPath(),Path.GetFileNameWithoutExtension(Path.GetTempFileName()));
Directory.Move(appPath, tmpDir);
Directory.Move(backupDir, appPath);
}
First we move the running application files to a random directory in Temp. Then we copy the backup folder to the application original directory. Of course, this will generate a .TMP file in the Temp directory of your device, and a folder with the actual running process. You will have to delete this temporary folder once in a while in production code.

Categories

Resources