Avoid max char limit c# - c#

To exceed the max path limit in c# you apparently need to concatenate your drive path with #"\\?\" at the beginning of it. If I do this then I get a drive path with the following at the front
\\\\?\\\\\\server\\share\\...
Now if I look for the file/folder it will fail because of illegal charachters in the path (I assume the ?) so how can I adopt the approach outlined on Microsoft's website (http://msdn.microsoft.com/en-us/library/aa365247(VS.85).aspx) correctly?
foreach (string filePath in Directory.GetFiles(folder))
{
String s = #"\\?\" + filePath;
if (filePath.Length > 255)
{
Console.WriteLine(filePath);
}
if (File.Exists(filePath))
{
FileInfo finfo = new FileInfo(s);
folderSize += finfo.Length;
}
}
foreach (string dir in Directory.GetDirectories(folder))
folderSize += GetDirectorySize(dir);

Standard System.IO doesn't support path longer than 260 characters.
But it seems there's a library with extended-length path support:
http://alphafs.codeplex.com/
I personally haven't tried it so far.

I don't think you should add all those slashes before the path, I think you did not understand everything what was written in MSDN here:
Maximum Path Length Limitation
In the Windows API (with some exceptions discussed in the following
paragraphs), the maximum length for a path is MAX_PATH, which is
defined as 260 characters. A local path is structured in the following
order: drive letter, colon, backslash, name components separated by
backslashes, and a terminating null character. For example, the
maximum path on drive D is "D:\some 256-character path string"
where "" represents the invisible terminating null character for
the current system codepage. (The characters < > are used here for
visual clarity and cannot be part of a valid path string.)
Note: File I/O functions in the Windows API convert "/" to "\" as part
of converting the name to an NT-style name, except when using the
"\?\" prefix as detailed in the following sections.
The Windows API has many functions that also have Unicode versions to
permit an extended-length path for a maximum total path length of
32,767 characters. This type of path is composed of components
separated by backslashes, each up to the value returned in the
lpMaximumComponentLength parameter of the GetVolumeInformation
function (this value is commonly 255 characters). To specify an
extended-length path, use the "\?\" prefix. For example, "\?\D:\very
long path".
Note: The maximum path of 32,767 characters is approximate, because
the "\?\" prefix may be expanded to a longer string by the system at
run time, and this expansion applies to the total length.
as you can read there,:
The Windows API has many functions that also have Unicode versions to
permit an extended-length path for a maximum total path length of
32,767 characters.
this is the key for your issue, if you need to create or access to a path longer than ~260 chars you should use specific Windows APIs.

Related

sony vegas script: probleme to get directory path

I d like to create a blind test generator with a script using Sony vegas 14. For this I must make my script in C#.
I don’t have many experiences in C# so maybe my problem is a very basic one.
To do my script I must use a library class (.dll) and execute my script by Sony vegas. To test my code easily I create a console app where I try my code and can easily print in the console what my code does.
For my program y need to get the path of all subdirectory in a Directory in a string.
My problem is the next one.
the command "Directory.GetDirectories" don't work
When I use the next code to check what in my array/list I get a coherent result if I use it in the console app version on my script (the number of subdirectories in my directory)
string[] dirs = Directory.GetDirectories(myDirectorypath, "", SearchOption.TopDirectoryOnly);// get all directory path in dirs
Console.WriteLine("the number of element in your array is "+ dirs.Length);
List<string> listdedossier = new List<string>(dirs); // convert the array in a list
Console.WriteLine("the number of element in your list is " + listdedossier.Count);
But when in paste my code in my dll project nothing is written in my array or my list. I notice this because when I want to print the number of elements in the list /array that return me 0
.
do you have any idea of what happen i my code?
thanks
You should check the online Microsoft documentation for GetDirectories. The 2nd argument is supposed to be a pattern to search for that conforms to Windows file name patterns. Essentially, all or part of a file name is allowed with * being a wildcard (The .* from regex meaning "match any character any number of times") and ? being a single character wildcard (regex .). You are providing an empty string, so you get nothing back. The pattern *.exe will match all executables in a folder (if you are using GetFiles, while the pattern pattern* matches any files/folders that start with pattern. If you want all directories, do this:
string[] dirs = Directory.GetDirectories(myDirectoryPath, "*", SearchOption.TopDirectoryOnly);
Next point, the path you provide can be either a relative path (e.g., "relative\path\to\folder"), an absolute path (e.g., "D:\path\to\folder"), or a fully qualified domain name (FQDN, e.g. "\servername.gov.edu.com\drive$\path\to\folder"). If you supply a relative path, you'll need to look up Windows' rules for path resolution. It is very easy using a relative path to search the wrong folder, or even a non-existent location (though you should get an exception in that case). Also remember: Windows path names are NOT case-sensitive.
Finally, when writing text with arguments, I HIGHLY recommend you use this format:
Console.WriteLine("The number of elements in your array is {0}", dirs.Length);
This uses a place holder in the string itself which has a numeric value in it. The number indicates what argument after the format string to use (0 is the first argument after the format string). You can use as many placeholders as you want, and use the same place holder in multiple locations. This is a more type-safe way to doing string printing in C# than using the + operator, which requires that an operator be defined that takes a string and whatever type you provided. When you use placeholders, WriteLine will use the built-in ToString method which is defined for all types in the Object class. Placeholders will always work, while using + will only sometimes work.

C# combining absolute and relative paths, Path.GetFullPath() inconsistent

I notice that when I use Path.GetFullPath(Path.Combine(#"c:\folder\","\subfolder\file.txt")) it returns a path c:\subfolder\file.txt, instead of the expected combined path c:\folder\subfolder\file.txt. It seems like having a '\' on the second combined input isn't handled by these methods. Has anyone come across this and found a better solution for merging paths?
var test1 = Path.GetFullPath(Path.Combine(#"C:\users\dev\desktop\testfiles\", #".\test1.txt"));
var test2 = Path.GetFullPath(Path.Combine(#"C:\users\dev\desktop\testfiles\", #"\test2.txt"));//
var test3 = Path.GetFullPath(Path.Combine(#"C: \users\dev\desktop\testfiles\", #"test3.txt"));
var test4 = Path.GetFullPath(Path.Combine(#"C:\users\dev\desktop\testfiles\",#".\XXX\test4.txt"));
var test5 = Path.GetFullPath(Path.Combine(#"C:\users\dev\desktop\testfiles\", #"\XXX\test5.txt"));//
var test6 = Path.GetFullPath(Path.Combine(#"C:\users\dev\desktop\testfiles\", #"XXX\test6.txt"));
var test7 = Path.GetFullPath(Path.Combine(#"C:\users\dev\desktop\testfiles\", #"\somefile\that\doesnt\exist.txt"));//
Results in
test1 is "C:\users\dev\desktop\testfiles\test1.txt"
test2 is wrong "\test2.txt"
test3 is "C: \users\dev\desktop\testfiles\test3.txt"
test4 is "C:\users\dev\desktop\testfiles\XXX\test4.txt"
test5 is wrong "c:\XXX\test5.txt"
test6 is "C:\users\dev\desktop\testfiles\XXX\test6.txt"
test7 is wrong "c:\somefile\that\doesnt\exist.txt"
Basically what I'm doing is combining a source path with individual file paths from a text file so that I can copy these files to a destination, and I want to maintain subfolder hierarchy.
e.g. common scenario of the files list being the same, but wanting to reference a specific source folder version.
source path + individual file path
\\myserver\project\1.x + \dll\important.dll
which should be copied to a destination in the same manner
c:\myproject\ + \dll\important.dll
So there would be variables; source, destination, files[array or list]
My current way forward is to use String.TRIM() method to remove special chars . \ / before combining paths with Path.Combine, Path.GetFullPath. But I thought maybe someone has realized a better way for a similar scenario.
It's also a pain creating the subfolders in the destination, basically im using String.LastIndexOf(#'\') to separate the filename from the foldername. Which is also seems a little sketchy, but a better way is beyond my experience.
Similar question:
Path.Combine absolute with relative path strings
Thanks to the feedback I now know that \file.txt is considered a fully qualified (absolute) path, which is why the combine method works that way.
A file name is relative to the current directory if it does not begin with one of the following:
A UNC name of any format, which always start with two backslash characters ("\\"). For more information, see the next section.
A disk designator with a backslash, for example "C:\" or "d:\".
A single backslash, for example, "\directory" or "\file.txt". This is also referred to as an absolute path.
https://msdn.microsoft.com/en-nz/library/windows/desktop/aa365247(v=vs.85).aspx#fully_qualified_vs._relative_paths
Based on the MSDN Documentation, this is expected behavior.
If path2 does not include a root (for example, if path2 does not start
with a separator character or a drive specification), the result is a
concatenation of the two paths, with an intervening separator
character. If path2 includes a root, path2 is returned.
Seperator characters are discussed in this MSDN article.
So let's take a look at your test cases:
var test1 = Path.GetFullPath(Path.Combine(#"C:\users\dev\desktop\testfiles\", #".\test1.txt"));
var test2 = Path.GetFullPath(Path.Combine(#"C:\users\dev\desktop\testfiles\", #"\test2.txt"));
Test1 is behaving correctly because it is taking the . as part of a valid file path and using it in combination with the first parameter to generate the combined path.
Test2 is behaving as expected because the \ is a separator character, so as described it is returned without the first parameter.
There is no functions that you like to use in .Net framework - trimming path or ensuring that relative path starts with ".\" your real options (probably library that does it exists somewhere).
Why code does not behave the way you like (not "wrong", just not meeting your unexpected expectations).
Combine need to decide which part of left path will stay and which will be replaced. It uses regular file system conventions to decide that (".", "..", "\" have special meaning for file paths)
Meaning of path starting with:
#"\" or"/" - starting from the root of current device - this covers most cases that you don't like
#".\" - means from current directory (hence after combining and normalizing it will behave exactly as you want)
`#"..\" (possible multiple "go up") - go up one folder - this is another case you'll likely disagree with.
any character that is not '/' or #'\' - file name or path from current folder
Also note that path ending on anything but "/" or #"\" is treated by Path.Combine as file path and when combined with other path it will lose last segment.

C# FileStream long paths

I'm having problem with my program, I'm creating backup system (Client send changed, created and renamed files to server and save them to server) but i'm not allowed save long paths and server crash (I can avoid crash with try/catch ofc) but I want save too long paths. How I can do it with FileStream?
My code:
user.CurrentFile.WriteStream = new FileStream(path + user.CurrentFile.FileName, FileMode.Create, FileAccess.Write, FileShare.None);
You can find more about file paths and file names on this msdn article
Here is the paragraph you may be interested in:
In the Windows API (with some exceptions discussed in the following
paragraphs), the maximum length for a path is MAX_PATH, which is
defined as 260 characters. A local path is structured in the following
order: drive letter, colon, backslash, name components separated by
backslashes, and a terminating null character. For example, the
maximum path on drive D is "D:\some 256-character path string < NUL>"
where "< NUL>" represents the invisible terminating null character for
the current system codepage. (The characters < > are used here for
visual clarity and cannot be part of a valid path string.)
One of workaround is to use command line to assign a drive letter to one of your subfolders.

C# Help needed changing code that deletes folders with long paths

A while back I asked a question on stackoverflow about deleting folders that have long paths (>260 characters), the most popular solution was to move into each directory to reduce the length of the path. I've struggled with this and I'm no further on, could someone please suggest how I would intergrate the suggested code into my code?
A typical path is:
\\serverName\share\dave\Private\Careers\Careers Ed\Fun Careers Education\Chris's not used 2006 to07\old 4.Careers Area Activity Week 1 30.10.06 or 6.11.06 or 13.11.06 Introduction to job levels and careers resources\Occupational Areas & Job levels Tutor Help Sheet[1].doc
Many thanks
//Suggested code:
var curDir = Directory.GetCurrentDirectory();
Environment.CurrentDirectory = #"C:\Part\Of\The\Really\Long\Path";
Directory.Delete("Relative\Path\To\Directory");
Environment.CurrentDirectory = curDir;
//My code:
try
{
var dir = new DirectoryInfo(#FolderPath);
dir.Attributes = dir.Attributes & ~FileAttributes.ReadOnly;
dir.Delete();
}
catch (IOException ex)
{
MessageBox.Show(ex.Message,"Delete Error",MessageBoxButtons.OK,MessageBoxIcon.Error);
}
Before 'removing a directory' we have to be sure that it is empty. You could consider using the reverse 'directory walk' approach.
This would entail dealing with each directory seperately in deep-to-shallow order.
Some pseudo code;
While (fullPath.Length > 0)
{
DirectoryToDelete = GetLastPartOfPath( fullPath );
CurrentDirectory = fullPath - DirectoryToDelete;
ChangeDirectory(CurrentDirectory);
DeleteDirectory(DirectoryToDelete);
fullPath = fullPath - DirectoryToDelete;
}
Hope this helps,
Have you tried using the long path name syntax ?
From the CreateFile function in the platform SDK:
Maximum Path Length In the Windows API
(with some exceptions discussed
later), the maximum length for a path
is MAX_PATH, which is defined as 260
characters. A local path is structured
in the following order: drive letter,
colon, backslash, components separated
by backslashes, and a terminating null
character. For example, the maximum
path on drive D is "D:\<256
chars>NUL".
The Windows API has many functions
that also have Unicode versions to
permit a maximum path length of
approximately 32,000 characters
composed of components up to 255
characters each in length. To specify
that kind of extended length path, use
the "\?\" prefix. For example,
"\?\D:\".
Note The maximum path of 32,000
characters is approximate, because the
"\?\" prefix can be expanded to a
longer string, and the expansion
applies to the total length.
To specify such a path using UNC, use
the "\?\UNC\" prefix. For example,
"\?\UNC\\". These
prefixes are not used as part of the
path itself. They indicate that the
path should be passed to the system
with minimal modification, which means
that you cannot use forward slashes to
represent path separators, or a period
to represent the current directory.
Also, you cannot use the "\?\" prefix
with a relative path. Relative paths
are limited to MAX_PATH characters.
The last paragraph is of course the one that is relevant to your case.
It is not sure that .NET supports this kind of path. You could use P/Invoke to call RemoveDirectory from the Win32 SDK.
Use ZetaLongPaths. It handles long paths. Google ZetaLongPaths

C#: Using Directory.GetFiles to get files with fixed length

The directory 'C:\temp' has two files named 'GZ96A7005.tif' and 'GZ96A7005001.tif'. They have different length with the same extension. Now I run below code:
string[] resultFileNames = Directory.GetFiles(#"C:\temp", "????????????.tif");
The 'resultFileNames' return two items 'c:\temp\GZ96A7005.tif' and 'c:\temp\GZ96A7005001.tif'.
But the Window Search will work fine. This is why and how do I get I want?
For Directory.GetFiles, ? signifies "Exactly zero or one character." On the other hand, you could use DirectoryInfo.GetFiles, for which ? signifies "Exactly one character" (apparently what you want).
EDIT:
Full code:
string[] resultFileNames = (from fileInfo in new DirectoryInfo(#"C:\temp").GetFiles("????????????.tif") select fileInfo.Name).ToArray();
You can probably skip the ToArray and just let resultFileNames be an IEnumerable<string>.
People are reporting this doesn't work for them on MS .NET. The below exact code works for me with on Mono on Ubuntu Hardy. I agree it doesn't really make sense to have two related classes use different conventions. However, that is what the documentation (linked above) says, and Mono complies with the docs. If Microsoft's implementation doesn't, they have a bug:
using System;
using System.IO;
using System.Linq;
public class GetFiles
{
public static void Main()
{
string[] resultFileNames = (from fileInfo in new DirectoryInfo(#".").GetFiles("????????????.tif") select fileInfo.Name).ToArray();
foreach(string fileName in resultFileNames)
{
Console.WriteLine(fileName);
}
}
}
I know I've read about this somewhere before, but the best I could find right now was this reference to it in Raymond Chen's blog post. The point is that Windows keeps a short (8.3) filename for every file with a long filename, for backward compatibility, and filename wildcards are matched against both the long and short filenames. You can see these short filenames by opening a command prompt and running "dir /x". Normally, getting a list of files which match ????????.tif (8) returns a list of file with 8 or less characters in their filename and a .tif extension. But every file with a long filename also has a short filename with 8.3 characters, so they all match this filter.
In your case both GZ96A7005.tif and GZ96A7005001.tif are long filenames, so they both have a 8.3 short filename which matches ????????.tif (anything with 8 or more ?'s).
UPDATE... from MSDN:
Because this method checks against
file names with both the 8.3 file name
format and the long file name format,
a search pattern similar to "*1*.txt"
may return unexpected file names. For
example, using a search pattern of
"*1*.txt" returns "longfilename.txt"
because the equivalent 8.3 file name
format is "LONGFI~1.TXT".
UPDATE: The MSDN docs specifiy different behavior for the "?" wildcard in Directory.GetFiles() and DirectoryInfo.GetFiles(). The documentation seems to be wrong, however. See Matthew Flaschen's answer.
The ? character matches "zero or one" characters... so from what you have I would imagine that your search pattern will match any file ending in ".tif" that is between zero and twelve characters long.
Try dropping another file in that is only three characters long with a ".tif" extension and see if the code picks that up as well. I have a sneaking suspicion that it will ;)
As far as the Windows search is concerned, it is most definately not using the same algorithm under the hood. The ? character might have a very different meaning there than it does in the .Net search pattern specification for the Directory.GetFiles(string, string) method.
string path = "C:/";
var files = Directory.GetFiles(path)
.Where(f => f.Replace(path, "").Length == 8);
A little costly with the string replacement. You can add whatever extension you need.

Categories