When I told one of my developer friends that I am going to write a post about the PathTooLongException, he found it rather amusing - how much could there really be to this Exception?

In Windows the full path of a file/folder can't be longer than 260 characters, this limit is enforced by the .net framework and normally by the operating system as well (one can't create a full path longer than 260 characters via windows explorer for example).

But recently however, I noticed a more interesting issue surrounding this exception while importing folders/files using a tool I wrote - quite a number of the paths exceeded the 260 character limit and obviously raised the PathTooLongException when the code attempted to import the folders/files.

Which obviously means that this limit can't exactly be set in stone.

After doing some digging (and playing around), I found its possible to circumvent the 260 limit programatically(Win32 API - Unicode via the "\\?\" prefix) and using 8.3 path names via the Windows console as well (upto aprox 32000 characters).

In the following snippet we succeed in creating paths longer than 260 characters via 8.3 file/folder names:

 
c:
cd\
md aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
cd aaaaaa~1
md aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
cd aaaaaa~1
dir c:\ > test.txt
 

The interesting thing (after running this snippet) on Windows XP/2003, is that one can't even browse to the file within the second folder - but on Windows 7/2008 (and I would imagine Vista as well) it was possible to browse to that file at least.

Now if we try to delete the folder (created via the previous snippet) using windows explorer, windows will swear at us (whoops you've just created a folder you can't remove, bwahaha).

Just joking, you will be able to remove those folders using the following snippet:

 
c:
cd\aaaaaa~1\aaaaaa~1
del test.txt
cd..
rd aaaaaa~1
cd..
rd aaaaaa~1
 

As for the second way (that I know of) to sidestep the 260 character limit, can be seen in the following extremely crude snippet (don't use as is) - via the Win32 API.

 
using System;
using System.IO;
using System.Runtime.InteropServices;
using Microsoft.Win32.SafeHandles;
 
public static class LongPath
{
static class Win32Native
{
[StructLayout(LayoutKind.Sequential)]
public class SECURITY_ATTRIBUTES
{
public int nLength;
public IntPtr pSecurityDescriptor;
public int bInheritHandle;
}
 
[DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
public static extern bool CreateDirectory(string lpPathName, SECURITY_ATTRIBUTES lpSecurityAttributes);
 
[DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
public static extern SafeFileHandle CreateFile(string lpFileName, int dwDesiredAccess, FileShare dwShareMode, SECURITY_ATTRIBUTES securityAttrs, FileMode dwCreationDisposition, int dwFlagsAndAttributes, IntPtr hTemplateFile);
}
 
public static bool CreateDirectory(string path)
{
return Win32Native.CreateDirectory(String.Concat(@"\\?\", path), null);
}
 
public static FileStream Open(string path, FileMode mode, FileAccess access)
{
SafeFileHandle handle = Win32Native.CreateFile(String.Concat(@"\\?\", path), (int)0x10000000, FileShare.None, null, mode, (int)0x00000080, IntPtr.Zero);
if (handle.IsInvalid)
{
throw new System.ComponentModel.Win32Exception();
}
return new FileStream(handle, access);
}
}
 

The interesting thing to note here, is that each segment created like this can't be longer than 255 characters(which is a bit longer than the folder names we can create via the 8.3 method) e.g. "c:\<255>\<255>\<255.ext>".

In the next snippet we apply the LongPath class as seen in the preceding snippet, which demonstrates how to access these files programmatically.

 
string path = @"c:\".PadRight(255, 'a');
LongPath.CreateDirectory(path);
 
path = String.Concat(path, @"\", "".PadRight(255, 'a'));
LongPath.CreateDirectory(path);
 
string filename = Path.Combine(path, "test.txt");
 
FileStream fs = LongPath.Open(filename, FileMode.CreateNew, FileAccess.Write);
 
using (StreamWriter sw = new StreamWriter(fs))
{
sw.WriteLine("abc");
}
 

Another interesting thing to note, is that one can't browse to the folders created in the preceding snippet, in any of the Windows Operating systems - it is however still possible to access them via the windows console using 8.3 file/folder names.

All of this is a bit of an ugly situation, infact most of the apps I tested didn't support reading/importing files affected by this issue. Is this an issue we must simply ignore?

Additional Reading
http://www.hanno.co.za/post/2011/04/04/Copying-files-with-very-long-filenames-paths.aspxhttp://msdn.microsoft.com/en-us/library/aa365247.aspx
http://blogs.msdn.com/b/bclteam/archive/2007/02/13/long-paths-in-net-part-1-of-3-kim-hamilton.aspx
http://vlaurie.com/computers2/Articles/filenames.htm

Windows OS PathTooLongException 转摘自http://www.cstruter.com/blog/308的更多相关文章

  1. Windows OS上安装运行Apache Kafka教程

    Windows OS上安装运行Apache Kafka教程 下面是分步指南,教你如何在Windows OS上安装运行Apache Zookeeper和Apache Kafka. 简介 本文讲述了如何在 ...

  2. DB Query Analyzer 6.03, the most excellent Universal DB Access tools on any Microsoft Windows OS

      DB Query Analyzer 6.03, the most excellent Universal database Access tools on any Microsoft Wind ...

  3. Windows/OS X下制作Mac安装U盘

    Windows下制作: 方法一:(适用于OSX 10.9以前) 前期准备:一台windows电脑 UltraISO软件 Mac系统镜像dmg(这里使用Mac os x 10.8.4) 至少8GB的U盘 ...

  4. Electron 从零创建一个 Windows/OS X/Linux 的桌面可执行程序

    [外链图片转存失败(img-3RucrgcX-1562556984462)(http://7vzsvy.com1.z0.glb.clouddn.com/electron-1-2.png "E ...

  5. Running a Remote Desktop on a Windows Azure Linux VM (远程桌面到Windows Azure Linux )-摘自网络(试了,没成功 - -!)

                              A complete click-by-click, step-by-step video of this article is available ...

  6. [ Windows] [ OS ] [ Remote Desktop ] 開啟同一個帳號同時2的連線RDP的方式

    感謝同事 Allen 的Support :) 執行>gpedit.msc 電腦設定>Windows元件>遠端桌面服務>遠端桌面工作階段主機>連線>限制遠端桌面服務的 ...

  7. 使用WIF实现单点登录Part II —— Windows Identity Foundation基本原理 -摘自网络

    在上一篇文章中,我们已经使用WIF构建了一个基于MVC4的简单的身份验证程序,在这篇文章里,我们将探讨一下到底什么是WIF,以及它的工作原理.然后在下一篇文章开始,我们将实际操作,实现单点登录功能. ...

  8. Tools - Windows OS

    001 - 文本操作 Ctrl + C / Ctrl + V / Ctrl + X / Ctrl + Z / Ctrl + A:复制/粘贴/剪贴/撤销/全选. 002 - 窗口分屏 使用快捷键 选中程 ...

  9. Windows OS系统变量

    %userprofile% C:\Users\Administrator\ %windir% C:\Windows\

随机推荐

  1. JS-04 JS中的函数都是按值传递的

    JS中的函数都是按值传递的 1.传递参数是基本类型 如例子:基本类型传入函数后,函数内部参数生成一个参数副本,把num变量的值赋给num参数,num参数再去参与函数中的运算,但不会影响外面num变量的 ...

  2. activiti 5.22 表结构解析及清空流程运行测试数据

    1.结构设计 1.1.    逻辑结构设计 Activiti使用到的表都是ACT_开头的. ACT_RE_*: 'RE'表示repository(存储),RepositoryService接口所操作的 ...

  3. Ubuntu14.04(nginx+php+mysql+vsftp)配置安装流程

    Ubuntu14.04(nginx+php+mysql+vsftp)配置安装流程 1.先切换到root用户 sudo  su 2.更新软件源 apt update apt-get upgrade 3. ...

  4. gcc版本切换

    查看安装的gcc版本 sudo update--alternatives --install /usr/bin/gcc gcc /usr/bin/gcc-5 100 显示所有版本gcc路径 sudo ...

  5. django框架常用的数据库迁移命令

    python manage.py makemigrations 默认所有修改过的model层转为迁移文件 python manage.py migrate   默认将所有的迁移文件都执行,更新数据库 ...

  6. Kvm --05 密码保护:Kvm管理之WebVirtMgr

    目录 密码保护:Kvm管理之WebVirtMgr 1. 前言 2. 特点 3. 功能 4. 部署 1).安装相关依赖 2).安装Python需求环境 3).配置Nginx 4). 远程连接 5).更新 ...

  7. Beta-星期五

    所属课程 https://edu.cnblogs.com/campus/xnsy/SoftwareEngineeringClass 作业要求  https://edu.cnblogs.com/camp ...

  8. Center OS 7

    1:关闭防火墙 systemctl stop iptables.service 2:禁止开启启动 systemctl disable firewalld.service 3:查看防火墙 firewal ...

  9. jQuery-Ajax请求Json数据并加载在前端页面,附视频教程讲解!

    Ajax技术应用广泛,这种异步加载技术,无需刷新网页即可更新网站内容,全局或者局部均可,所以大家应该学会这种技巧,把技术用上来. 创建demo.json文件,用来做数据源: {     "t ...

  10. 洛咕P4180 严格次小生成树

    鸽了很久的一道题(?)貌似是去年NOIP前听的emm... 首先我们分析一下最小生成树的性质 我们kruskal建树的时候呢是从小到大贪心加的边,这个的证明用到拟阵.(我太菜了不会) 首先我们不存在连 ...