MAX_PATH of Windows

Source: Internet
Author: User
Tags microsoft website

MAX_PATH Explanation: File name is the longest (ANSI), plus the drive letter (x:\) 3 bytes, 259 bytes, plus the Terminator 1 bytes, total 260
http://msdn.microsoft.com/en-us/library/windows/desktop/aa365247 (v=vs.85). aspx
http://support.microsoft.com/kb/320081


Under Windows, the character length of the full file name is limited, as is known to be max_path,260. For this, a few specific explanations:
1. This 260 refers to the full path character length that contains the directory to the file name.
2. In fact, testing can be found:
--plus null, you can only create a 259-character full-text name in the Explorer, that is, you can actually only create a path of max_path-2 = 258 characters.
--You can create a C: \ Long directory \abc.txt <= 258, or you can create a c:\abc\ long file name,. txt <= 258.
--when creating each level of the directory, you can enter a directory name character is limited, the rule is: at least 11 characters left (8.3 rule?). Allows the most in-layer catalogs to still create files.
--but, for example, if you create a C:\abc\ long file name,. txt, and then rename the directory ABC, you can create a full-text name with a total length of more than MAX_PATH. Quite tricky.

Reference: Http://blog.163.com/[email protected]/blog/static/3606944620105109561679/


------------------------------Solution One------------------------------
Http://www.debugease.com/csharp/1202792.html
Then you don't use its full path to create, with a folder of DirectoryInfo to create it.
Thank you for reminding me to get the parent folder path Createsubdirectory. Tried a lot of ways, how to forget this, sweat yourself.

Let's start with an interesting anomaly in the BCL: [PathTooLongException]: The specified path, file name, or both is too long. The fully qualified file name must is less than 260 characters, and the directory name must is less than 248 characters. we Customers in the bug report said: "The path is only 260 characters?" It's funny, Ms. Make this restriction a bit longer! ". Here I will explain the problem to the people who submitted the bug report (I'm sorry your bug was turned into "won fix") and tell you about our efforts. Let's first clarify some of the terms: path: The full path of a file. For example, you have another file: C:\temp\fileA.txt, then usually you will call this file FileA.txt, but its full path should be c:\temp\fileA.txt.
The Max_path:windows API defines the maximum length of a path, 260 characters.
Long path: A path that exceeds the MAX_PATH length.
Long file name: Not the same as long path. This is actually used to compare with the short file name, which is the 8.3-format filename we said before.
It is well known that the. NET API is dependent on the Windows API, and from this point of view, there is no problem with this exception. However, the Windows API also provides a way to circumvent this max_path limitation. If you prefix the "\\?\" in front of your file path and then call the Unicode version of the Windows API, the maximum length of your path can reach 32k. That means you can use long path with the prefix "\\?\" in the Windows API. No one complains about the length limit of 32k, so is it possible to say that the problem is solved? It's not exactly. There's a reason we didn't want to support long path in the past, and now we'll consider these reasons. The first reason is security. The prefix "\\?\" is not just the limit of the broken long path, but it also allows path to be only minimally modified by the Windows API before it reaches the file system. The result of this is that "\\?\" circumvents the Windows API's series of standardized operations on path: Remove the space behind the path and put '. ' and ' ... ' Extend to the corresponding content, and convert the relative path to the perfect path, and so on. In. NET if we use FileIOPermission attribute to ensure security, we have to use a standardized path. Without FileIOPermission, there will be security implications. Now we understand that if we use the prefix "\\?\" to solve the problem of long path, we must be able to standardize the path like the Windows API. The second reason is to support inconsistent behavior that long path can cause. Many of the Windows APIs that manipulate files support a long path prefixed with "\\?\", but only a lot, not all. For example, LoadLibrary, whose function is to map a module to the caller's address space, will fail when the file path exceeds MAX_PATH. This means that you can call MoveFile to put a DLL in a path longer than MAX_PATH, but it fails when you want to load the DLL. There are many such examples in Windows API, although there are some workarounds, but are specific problems, there is no common solution. Another factor, and also the most painful one, is the Windows application and Windows shell itself in a long Compatibility on path. Because the Windows shell itself supports only longThe path of less than 260 (the Vista shell weakens this limitation). That means if. NET supports long path, you can create some files that you cannot access in Explorer or on the command line through your. NET App. J we have realized that the 260-character limit is not very reasonable. Our customers do not often encounter this problem, but once a path beyond MAX_PATH is needed, it is inconvenient. One expedient is to p/invoking the Windows API and use the "\\?\" prefix, but this will have to write a large lump of code that repeats with System.IO. So in order to solve this problem, our customers often redesign the directory structure, racking their brains to shorten the directory name. Because the problem is becoming commonplace, MS has already begun to address this issue, whether in the. NET Framework or elsewhere. In fact, in Vista you should already be able to see the changes we've made to reduce the odds of a MAX_PATH problem: Many specific directory names have been shortened (\documents and Settingsà\users, in fact, In MS There is a special alias called Longpath to talk about this problem), the shell also has a auto-path shrinking function, it will use a shorter alias to represent the path to the long path to compress those 260 characters.


------------------------------Solution Two------------------------------
Http://express.ruanko.com/ruanko-express_11/webpage/tech-overnight_1.html

Upper-level logic control and transactional processing are developed using Java, and the underlying core functionality is implemented in C + +, which has become a more general development model. However, because of the default settings of the Windows operating system, the above languages encounter some problems with the processing of long pathname (>260 character) files. This article lists the differences between the different JDK versions on the Windows operating system for long path name file processing, gives two C + + programming methods that support long pathname files, and indicates that long path names are fully supported from JDK 5.0. Using the method of this article, we can solve the limitation of the standard API function on the Windows platform to support the long pathname file, which is convenient for the development testing work.

Windows restrictions on long path name files

As is known to all, Microsoft's file system has undergone fat->fat32->ntfs technological change. And regardless of the security and the way of file organization innovation, the file name alone has been changed from the old DOS 8.3 file format (only the longest 8 characters and 3 character suffix name) to support a file name of up to 255 characters. For path lengths, NTFS also supports path names up to 32,768 characters long.

However, the Windows operating system does not completely release the limit for pathname length, and in windef.h, you can find the following macro:

#define MAX_PATH 260

In fact, all Windows APIs follow this limitation. Therefore, whenever we try to change the file name, the input filename length (full path) reaches a certain limit, although the file name itself has not reached the limit of 255 characters, but any input will no longer be accepted, this is actually because the operating system does not allow 260 characters (byte) of the file full path.

In practical applications, the 260-character full path limitation has caused great inconvenience to the application development. Consider the following application: We want to add a local cache feature to the application server, which can leave a local copy of the file on the remote server. A reasonable implementation can map the URL to a file name, and when the URL is long, the length of the cache file will be very long. When the file name is longer than 255, we can use the first 255 characters of the mapped file name as the directory names. However, we still cannot resolve the full path limit of 260 characters. Also, if the directory structure of an application is too deep, it is easy to have some file name lengths (with paths) longer than 260 characters, and thus cause installation or deletion failures. In a word, this limitation has caused a lot of inconvenience to our development and testing work.

For some Web servers, Java code is often used for the development of upper-level logical control/transaction processing, while the C + + is used for the implementation of the underlying core functionality. For this reason, we have studied the support of these two programming languages for long path name files. Among them, for Java, compared with two common versions of 1.4 and 5.0 for long path support of the differences, the limitations of C + + language, we proposed the solution.

Experimental environment

Operating system: Windows XP
File System: NTFS file System
Java Compilation environment: JDK 1.4.2 and JDK 5.0
C + + compilation Environment : Vc.net
Using long path name files in Java

The Java language does not require special processing of long pathname files to support basic operations such as the creation, read-write, and delete operations of long path names. However, JDK 1.4.2 and JDK 5.0 are different on long path support, JDK 1.4.2 does not fully support all long pathname file operations, such as accessing file attributes is not supported. We have designed the following code to verify the differences between JDK 1.4.2 and JDK 5.0 for long pathname file support.

Listing 1. Java Experiment code for long path name file operation:

try {String fileName = "E:\\verylongpathverylongpathverylongpath Verylongpathverylongpathverylongpathverylongpa Th verylongpathverylongpathverylongpathverylongpath\verylongpathverylongpathverylongpathvery LongpathVerylon    Gpathverylongpathverylongpathverylongpathverylongpathverylongpathverylongpa Th.txt ";    SYSTEM.OUT.PRINTLN ("FileName:" + filename);    System.out.println ("File path length:" + filename.length ());         String renamefilename = "E:\\verylongpathverylongpathverylongpath Verylongpathverylongpathverylongpathverylongpath    Verylongpathverylongpathverylongpathverylongpath\\short.txt ";    Create the file.    File File = new file (fileName);    if (!file.exists ()) file.createnewfile ();    if (file.exists ()) System.out.println ("The File exists!");    if (File.canread ()) System.out.println ("The file can be read!");    if (File.canwrite ()) System.out.println ("The file can be written!");    if (File.isfile ())    System.out.println ("It ' s a file!");    Write to the created file.    FileOutputStream out = new FileOutputStream (file);    PrintStream p = new PrintStream (out);    P.println ("This was only a test!");    P.close ();    Read the information from that file.    BufferedReader br = new BufferedReader (new FileReader (file));    StringBuffer sb = new StringBuffer ();        while (true) {String SL = Br.readline ();        if (SL = = null) {break;        } else {sb.append (sl + "\ n");    }} br.close ();    System.out.println ("The content in the" file: ");    System.out.print ("\ T" + sb.tostring ());    File Rename File NewFile = new file (renamefilename);    if (newfile.exists ()) System.out.println (Renamefilename + "exsited");        else {if (File.renameto (NewFile)) {System.out.println ("Rename sucessful!");        } else {System.out.println ("Rename failed!"); }}//delete file if (File.delete ()) SyStem.out.println ("The old file deleted!");    if (Newfile.delete ()) System.out.println ("The renamed file deleted!");        } catch (IOException e) {//error happened e.printstacktrace ();    System.out.println ("Error occurs in writing to the file."); }}

Listing 2. Results of using jdk1.42

Filename:e:\ Verylongpathverylongpathverylongpathverylongpathverylongpathverylongpathverylongpathverylongpathverylongpathverylongpathv Erylongpathverylongpathverylongpathverylongpathverylongpathverylongpathverylongpathverylongpathverylongpathverylongpathve RylongpathVerylongpath.txt
File Path length:272
The content in the file:
This was only a test!
Rename failed! The old file deleted!

From the experimental results, JDK 1.4.2 Gets the contents of the long pathname file, so it is supported for the creation of the long pathname file and for read and write operations. However, comparing the results of using JDK 5.0 below, you can see that all the judgments on file properties are wrong, and the renamed operation is not possible. More importantly, there is a fatal problem with JDK 1.4.2 that the method file.exists () is invalid. In general, before deleting a file, you need to call the method to determine whether the file exists, for the JDK 1.4.2, if you go directly to delete a file that does not know whether or not, there will be a relatively large risk. Therefore, JDK 1.4.2 on the Windows platform for long path file operation is only limited support, when used, be sure to pay attention to.

Listing 3. Results of using jdk5.0

Filename:e:\ Verylongpathverylongpathverylongpathverylongpathverylongpathverylongpathverylongpathverylongpathverylongpathverylongpathv Erylongpathverylongpathverylongpathverylongpathverylongpathverylongpathverylongpathverylongpathverylongpathverylongpathve Rylongpathverylongpath.txtfile path Length:272the file exists! The file can be read! The file can be written! It ' s a file! The content in the File:this are only a test! Rename sucessful! The renamed file deleted!

It is clear from the experiment that in version JDK 5.0, all file operations (new, read-write, attribute manipulation, renaming, deletion, etc.) are handled correctly. With JDK 5.0, you don't have to worry about the use of long pathname files at all.

Using long path name files in C + +

Long pathname files can be supported with no changes relative to JDK 5.0, and files with a path length of more than 260 characters will be much more complex in C/s + +. Here are two ways to support long path name files.

Method One: Use the Unicode version of the API

From the official Microsoft website Path Field Limits, you can find that using the Unicode version of the API for Windows NT 4.0 with the NTFS file system, Windows $, Windows XP Home Edition, W indows XP Professional and Windows Server 2003 operating systems can support 32768-byte file path lengths. Also, the pathname must use the \\?\ prefix. According to this idea, we designed the experiment.

Listing 4. Sample code for C for long path name file operation (Unicode API)

 {FILE *from, *to;char filename[1024];strcpy (filename, "\\\\?\\e:\\verylongpathverylongpath 
Verylongpathverylongpathverylongpathverylongpathverylongpathverylongpathverylongpathverylongpathverylongpath
\\VerylongpathVerylongpathVerylongpathVerylongpathVerylongpathVerylongpath
VerylongpathVerylongpathVerylongpathVerylongpathVerylongpath.txt "); int Il1=multibytetowidechar (CP_ACP, 0, FileName,
strlen (filename), NULL, 0); wchar* Wfilename=new wchar[il1+1]; WFILENAME[IL1] = ' + '; int Il2=multibytetowidechar (CP_ACP, 0, filename,
strlen (filename), wfilename, iL1); from = _wfo Pen (wfilename, L "RB"), to = fopen (". \\longpath.txt", "WB"); if (from ==null) | | (To==null)) Return-1;char buffer[1024];int count = 0;while ((count = fread (buffer, sizeof (char), 1024x768, from))! = 0) fwrite (buffe R, sizeof (char), count, to);d elete []wfilename;fclose (from); Fclose (to);}

Using the method above, we can copy a file with a long path name into the current folder. From the test results, the method is effective. However, because this method requires the system to use the Unicode API, you also need to change the path name and encoding method. Therefore, for a system that already exists, the changes will be significant because of the need to change the APIs associated with all file operations.

Method Two: Create a short path name in 8.3 format

For each long pathname, there is a 8.3 format (8-character file name and 3-character suffix name) corresponding to the short path name, any folder or file name can be mapped to a 8-character file name (a~b), where a is the filename prefix, B is the order of the alphabetic order. The operating system can guarantee that such mappings are one-to-two, as long as you use GetShortPathName () to convert the long path name to the corresponding short path name, you can perform normal file operations on the file. At the same time, you can use the function getlongpathname () to restore the short path name of the 8.3 format to the initial long path name at any time.

As GetShortPathName Function describes, we need a Unicode version of the API, while the path name with the prefix \\?\, in order to achieve the long and short path between the name of the switch. However, from an experimental point of view, even if you do not use the Unicode API, you can still achieve these functions.

Listing 5. Example code for C for long path name file operation (ShortPath)

 {char pathName [1024];strcpy (PathName, "\\\\?\\e:\\verylongpathverylongpathverylongpath 
Verylongpathverylongpathverylongpathverylongpathverylongpathverylongpathverylongpathverylongpath
\ \ Verylongpathverylongpathverylongpathverylongpathverylongpathverylongpathverylongpath
VerylongpathVerylongpathVerylongpathVerylongpath.txt "); const int maxpathlength = 2048;char Shortpath[maxpathlength] ; if (strlen (pathName) >= max_path) {char prepath[] = "\\\\?\\"; if (strlen (pathName) >= Maxpathlength-strlen (PathName)) return false; sprintf (ShortPath, "%s%s", Prepath, PathName); for (int ipathindex = 0; Ipathindex < strlen (shortpath); ipathindex++) if (shortpath[ipathindex] = = '/') Shortpath[ipathindex] = ' \ \ '; int dwlen = GetShortPathName (ShortPath, ShortPath, maxpathlength); if (dwlen <= 0) return false;}}

After the above code, the path name exceeding the MAX_PATH limit can be converted to a short pathname in the 8.3 format, which can be used as a parameter to the subsequent file operation function (ShortPath). In this case, all operations on the file can be supported. We solved the problem of long pathname file operation by shortening the length of path name.

Conclusion

This article first lists the different JDK versions on the Windows operating system for long pathname file processing differences, but also pointed out that JDK 5.0 to fully support the long path name, in the second part of the two support for long path name file C + + programming method. Using any of the methods above, we can implement the long pathname file operation, which will greatly facilitate our development work, to solve the standard API functions on the Windows platform for long pathname file support limitations.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.