The system cannot find the path specified - c#

I am trying to calculate sha1 hash for some of the files from location %system%\drivers\ using C#. I know files are at the exact location but when i use
FILE.Exists("c:\\Windows\\System32\\Drivers\\1394ohci.sys")
it always retuns false.
C:\Users\administrator>dir c:\Windows\System32\drivers\1394ohci.sys
Volume in drive C has no label.
Volume Serial Number is 5A4F-1E60
Directory of c:\Windows\System32\drivers
11/21/2010 08:53 AM 229,888 1394ohci.sys
1 File(s) 229,888 bytes
0 Dir(s) 19,521,245,184 bytes free
C:\Users\administrator>fciv -sha1 c:\Windows\system32\drivers\1394ohci.sys
//
// File Checksum Integrity Verifier version 2.05.
//
c:\windows\system32\drivers\1394ohci.sys\*
Error msg : The system cannot find the path specified.
Error code : 3
I even tried fciv.exe on the file and it also generate the same output. I tried running the command as administratror but it did not help.
I did lot of web search but nothing worked. Please help and let me know how to fix this issue.
Appreciate your help.
Thank you,

If I understand your problem correctly then you need to look at File System Redirector
The %windir%\System32 directory is reserved for 64-bit applications.
Most DLL file names were not changed when 64-bit versions of the DLLs
were created, so 32-bit versions of the DLLs are stored in a
different directory. WOW64 hides this difference using a file
system redirector.
In most cases, whenever a 32-bit application attempts to access
%windir%\System32, the access is redirected to %windir%\SysWOW64.
Access to %windir%\lastgood\system32 is redirected to
%windir%\lastgood\SysWOW64. Access to %windir%\regedit.exe is
redirected to %windir%\SysWOW64\regedit.exe.
Also there is small sample at the bottom of page if you can try that one
string system32Directory = Path.Combine(Environment.ExpandEnvironmentVariables("%windir%"), "system32");
if(Environment.Is64BitOperatingSystem && !Environment.Is64BitProcess)
{
// For 32-bit processes on 64-bit systems, %windir%\system32 folder
// can only be accessed by specifying %windir%\sysnative folder.
system32Directory = Path.Combine(Environment.ExpandEnvironmentVariables("%windir%"), "sysnative");
}

As others have mentioned, this is the file system redirector at work. The workaround is to replace system32 with sysnative in the filepath.
This was driving me bonkers too, and it took too much work to find the simple workaround. I kept landing on pages with advanced scripting and complicated, obscure tangentially-related solutions. So I thought I'd share the "easy mode".

Run your program in Administrator Mode.

From http://msdn.microsoft.com/en-us/library/system.io.file.exists.aspx:
The Exists method returns false if any error occurs while trying to determine if the specified file exists. This can occur in situations that raise exceptions such as passing a file name with invalid characters or too many characters, a failing or missing disk, or if the caller does not have permission to read the file.

Related

Programatic truncation of large file names (zipped) for different Windows editions

So I'm bugfixing on a program that allows a user to create an Excel document, which it first zip compresses before serving to the customer. One of the client complaints is that, while the zip file can always be downloaded, sometimes the user must copy the Excel file out of the archive (or extract it) before opening it, using the standard Windows compressed tools. Standard "File name too long" error.
The algorithm is, of course, setting the .zip archive name to the same as the report - which can be 100+ character long strings.
The solution I'm implementing is to check the length of the potential report to see it if it violate MAX_PATH, naturally, and truncate the .zip name as needed.
Testing it on Windows 7, this works perfectly. But something odd happens when testing it under 8.1
It still throws an error trying to open from the archive - but this error is a bit more enigmatic.
"Sorry, we couldn't find C:\Users{My user name}\AppData\Local\Temp\Temp1_{Rest of the truncated archive name}.zip{Full file name}.xlsx. Is it possible it was moved, renamed or deleted?"
This error keeps popping up, regardless of whether the file is "Open"ed or "Save"d from the browser.
Normally, I'd just try further tweaking, but testing on the Windows 8.1 platform involves a lot of overhead at the moment, and it doesn't look like the problem is the path name length.
What is going on? Does Windows 8 have problem with the length of names within archives, or...?
Also, the reason I am posting this here, and not, say, User Experience, is because I feel like the solution will be programmatic - something in the code of the program. I readily concede that "allow the end user to skip hitting the Extract button" is about providing an easy user experience, but truncating the length of the entire path solved the problem on Windows 7.
Just not 8.1, and googling/searching the SO site family provides no help - ironically, because of the keyword Excel.
So, as I found in the link above (http://answers.microsoft.com/en-us/office/forum/office_2013_release-excel/sorry-unable-to-find/595333d0-1463-499f-967e-4da8ac2e2047?auth=1) the crux seems to be that, although MAX_PATH is 260 characters, Excel 2013 can't handle anything over 212.
I still haven't been able to give this the rigorous testing it deserves, but if anyone else encounters this problem, and finds this page in their quest for a fix, just truncate until the entire path is under 212 and you should be good.

Run a program from an array of bytes without creating a temporary file . c#

I have many .exe files stored on IIS server (MSSQL) that contain reports and access to the file(s) on the servers . (These files will be change on Sundays .)
After connecting to the SQL Server and choosing an .exe file , I am Downloading(Select in SQL) , Now I have an array of bytes that assigned to a variable .
I cant creating a temporary file like "temp.exe" in an unknown directory because I know there are many ways to understand a new created file directory and ...
It is not secure because my users are professional and if one of them know these ways ...
So , I want know is it possible to run an .exe file from an array of bytes (as default as running from "Windows Explorer") without creating a temporay file ?!
tnx
update : Exe files are .net and Manager will be upload new files or change files .
Be warned that your belief of any extra security is illusory. If the user has access to the machine to read files, they will also be able to read the memory of your process.
However, to answer your question, what you are asking to do is simple enough and described here: Load an EXE File and Run It from Memory.
In essence you do the following:
Pass your byte array to Assembly.Load to create a new Assembly.
Read the entry point of that assembly using the EntryPoint property.
Create an instance using Assembly.CreateInstance, and invoke the method on that instance.
The code looks like this:
Assembly a = Assembly.Load(bytes);
MethodInfo method = a.EntryPoint;
if (method != null)
method.Invoke(a.CreateInstance(method.Name), null);
Doesn't sound safe either way, why are you storing exécutables in a db to begin with? Who uploads them? Wether they're on the filesystem or not they're just as dangerous if malicious.
Are those .net exes? If so you could load the assembly into a child appdomain with security restrictions and i'm pretty sure you can do that without copying to disk.
For regular native exe i don't think it's possible to just launch an exe without a physical file backing it (even in the task manager you can see the path from which a program was launched)
There are two different concerns for security here:
That someone can see the file that you've downloaded from the database.
That executing the file might be a security threat.
For the first concern: Create a directory on the server and restrict access to that directory so that no one but the user account that runs your server program can see/use it. Save the byte array into a temporary file in that directory, execute it, and once the process has completed, delete the temporary file.
For the second concern: You'll need to run that executable in a sandboxed environment. In .NET you can run code in a sandboxed environment by loading the code into a separate AppDomain that you've setup to only have partial trust. How to do that deserves another question on SO though.

Strange behavior from .NET regarding file paths

I couldn't find any information on this through professor Google, so here I am. Take the given path name and paste it into Windows Explorer. I stumbled across this after discovering bug in my code that generated the paths with an extra '.' in the path name before a directory \ separator...
#"C:\\pathto.\file.ext"
In code, .NET will accept the path when calling File.Create and a file will be generated, but at this path:
#"C:\\pathto\file.ext"
Copying C:\\pathto.\file.ext into Windows Explorer's address bar and watch the '.' disappear and take you to C:\\pathto\file.ext
Is it normal behavior for .NET and Windows to It's not causing an issue because the '.' is being removed by both .NET and Windows when passed into file operations. The real issue is that all the files in the DB have filenames with a '.\', but exists in paths that do not have a '.\'... and File.Exists() works too, although the path is not the 'real' physical location...
What's going on here?
This is a "feature" of the Windows file system. MSDN:
Do not end a file or directory name with a space or a period. Although the underlying file system may support such names, the Windows shell and user interface does not. However, it is acceptable to specify a period as the first character of a name. For example, ".temp".
All normal Windows APIs ignore/remove trailing dots in the file/folder names when regular path is passed in.
If you really need support for trailing dot you need to use "\\?\" prefixed paths and interop all calls yourself (as .Net does not support this file format). See MSDN: Naming Files, Paths, and Namespaces, How to delete a folder that name ended with a dot (".")? and You cannot delete a file or a folder on an NTFS file system volume for more info.
Here is related question showing how to PInvoke function that accepts long file path: c# call Win32 API for long file paths?

Access to the path denied error in C#

I have read a similar post, but i just cant figure out the problem.
I have changed the windows permissions and changed routes.
When i try to save a file it throws me the exception:
Access to the path **** denied.
string route="D:\\";
FileStream fs = new FileStream(route, FileMode.Create); <--here is the problem
StreamWriter write = new StreamWriter(fs);
patient person = new patient();
patient.name = textBox1.Text;
patient.name2 = textBox2.Text;
You are trying to create a FileStream object for a directory (folder). Specify a file name (e.g. #"D:\test.txt") and the error will go away.
By the way, I would suggest that you use the StreamWriter constructor that takes an Encoding as its second parameter, because otherwise you might be in for an unpleasant surprise when trying to read the saved file later (using StreamReader).
Did you try specifing some file name?
eg:
string route="D:\\somefilename.txt";
tl;dr version: Make sure you are not trying to open a file marked in the file system as Read-Only in Read/Write mode.
I have come across this error in my travels trying to read in an XML file.
I have found that in some circumstances (detailed below) this error would be generated for a file even though the path and file name are correct.
File details:
The path and file name are valid, the file exists
Both the service account and the logged in user have Full Control permissions to the file and the full path
The file is marked as Read-Only
It is running on Windows Server 2008 R2
The path to the file was using local drive letters, not UNC path
When trying to read the file programmatically, the following behavior was observed while running the exact same code:
When running as the logged in user, the file is read with no error
When running as the service account, trying to read the file generates the Access Is Denied error with no details
In order to fix this, I had to change the method call from the default (Opening as RW) to opening the file as RO. Once I made that one change, it stopped throwing an error.
I had this issue for longer than I would like to admit.
I simply just needed to run VS as an administrator, rookie mistake on my part...
Hope this helps someone <3
If your problem persist with all those answers, try to change the file attribute to:
File.SetAttributes(yourfile, FileAttributes.Normal);
You do not have permissions to access the file.
Please be sure whether you can access the file in that drive.
string route= #"E:\Sample.text";
FileStream fs = new FileStream(route, FileMode.Create);
You have to provide the file name to create.
Please try this, now you can create.
TLDR : On my end, it had something to do with AVAST ! => Whitelist your application.
All of a sudden, I also got this UnauthorizedAccessException problem in the windows WPF program I'm writing. None of the solutions worked - except I couldn't figure out how to elevate my application to full privileges (not using VS) while at the same time, being already on the administrator account, I didn't feel the need to dig that deep in permission concerns.
The files are image files (jpg, psd, webp, etc.) I wasn't trying to open/write a directory, it has always been a valid path to a file, and I needed to write to the file, FileAccess.ReadWrite was inevitable. The files (and any of their parent directory) were not readonly (I even checked by code prior calling new FileStream(path, mode, access, share) via FileInfo.IsReadOnly) - so what happenned all of a sudden ???
Thinking about : I had an had drive crash, so I unpacked a backup of my solution code from another drive. In the meantime, I added codes in my application to PInvoke APIs to directly read hard drive sectors physical bytes as well as USB plug/unplug monitoring.
I started to get the Exception when I added those, but even though I temporarly removed the related codes from the application, I still got the UnauthorizedAccessException.
Then I remembered one thing I've done long ago, a painstaking similar issue where I wanted my application to communicate sensible data via Wifi, which was to add the executable among AVAST exceptions, and the assembly directory aswell (My app was already among the authorized apps through firewall)
Just did it for my application in AVAST settings, AND THE EXCEPTION IS GONE !!! Two whole days I'm lurking StackOverflow and the web to get moving on, FINALLY !
Details : I can't pinpoint exactly what AVAST didn't like in my application as the only changes I made :
Retrieved then launched the backup code - it worked like a charm, files (images) opens/write without problems (3 days ago)
Added USB detection (3 days ago - Just tested the code, didn't tried to open an image)
Added PInvoke physical drive direct read (2 days ago - FileStream, and the logic to define where/how to scan the damaged drive - Just tested the code, didn't tried to open an image)
Added image format detection starting from Jpg/Jfif.. 2 days ago, got the exception upon testing the code.
While searching for solutions, added an Image Gallery WPF UserControl to diplay pictures based on their signature and check which files gives the exception : almost all of them (some files opens/write okay - why ???)
Tried everything I've found on SO (since the last 2 days) until I opened AVAST settings and whitelist my application.
... now I can move on into adding a bunch of file signatures to retrieve as many datas as I could.
If this may help those who like me, aren't failing on the "I'm passing a directory path instead that of a file", yet, have no time to learn exactly why antiviruses think our own code is a malware.
Just Using the below worked for me on OSX.
var path = "TempForTest";

Directory.SetCurrentDirectory throws PathTooLongException

There are several related questions on stackoverflow but either my situation is different or I am too dumb to relate those to situation. I am hoping someone can help me with this. Further I am not even much of a .NET developer so I apologize in advance for any wrong terminology use.
My scenario is as follows: The tool that is used to deploy our .net application (One Click?) puts it in a directory whose full name exceeds 300 characters. The application uses a third party component -- lets call it dbstore -- that processes the specified file that resides in the application deployment directory.
So far we were using Assembly.GetExecutingAssembly().GetName().CodeBase to construct the fully qualified name of the file to pass to dbstore. But dbstore uses old style APIs and fails when it tries to open the file.
Since dbstore is not expected to change soon, it was recommended that the application chdir to the deployment directory and pass a relative path name in current directory to it. This is also the approach described in the accepted response PathTooLongException in C# code
However I find that Directory.SetCurrentDirectory also throws PathTooLongException. This happens even when I am using UNC path name, e.g a name starting with \\?\0000000000000\...
Am I doing something fundamentally wrong? Is there another function to use?
EDIT: It seems there is no way to achieve what I am looking for. Far as I can tell there is no way to set current directory to a long path.
Do you get a similar result when using Environment.SetCurrentDirectory() ?
If so, you may want to change your directory subfolder after subfolder.
EDIT:
Windows actually sets a limitation of 255 chars for a file path (WinXP) or 260 chars (Vista).
Note that this limitation does not apply for the filesystem, so you can have a file stored in such a long directory path, but Windows Explorer and many Windows services cannot read from such path.
Actually it seems to also include .NET framework methods since you cannot access such files. You may need to write your own filesystem API, but that's a bit too much overhead. Can't you just shorten the file path ? Does Windows offer a shortened way to address a file (like 8 octet file names) ?
Source: http://labnol.blogspot.com/2006/10/limitations-with-long-file-names-on.html

Categories