C# 如何调用PathTooLongException?

C# 如何调用PathTooLongException?,c#,.net,windows,path,pathtoolongexception,C#,.net,Windows,Path,Pathtoolongexception,我有一个小的实用程序,它不断地点击PathTooLongException,我被指示输出错误的文件路径,使用它很好。。。有点 然而,我发现自己无法复制这个问题。我尝试创建一个路径大于MAX_路径的文件,但我的程序处理得很好。我试图进一步增加路径大小,但Windows不允许这样做,关键是通过CMD甚至不能进入包含文件夹,因为在那之前我确实点击了PathTooLongException,但我的程序处理得很好,没有引发异常 真正奇怪的是,尽管从未抛出异常,但程序只是忽略了有问题的文件,这是一种代码的平

我有一个小的实用程序,它不断地点击PathTooLongException,我被指示输出错误的文件路径,使用它很好。。。有点

然而,我发现自己无法复制这个问题。我尝试创建一个路径大于MAX_路径的文件,但我的程序处理得很好。我试图进一步增加路径大小,但Windows不允许这样做,关键是通过CMD甚至不能进入包含文件夹,因为在那之前我确实点击了PathTooLongException,但我的程序处理得很好,没有引发异常

真正奇怪的是,尽管从未抛出异常,但程序只是忽略了有问题的文件,这是一种代码的平静,它无法找到异常,也不会抛出错误

string fileName;
DirectoryInfo di = new DirectoryInfo(strFolderPath);
IEnumerable<FileInfo> fileList = di.EnumerateFiles("*", SearchOption.AllDirectories);
foreach (FileInfo fi in fileList)
{
    fileName = fi.FullName.Remove(0, di.FullName.Length + 1);
}
下面是SyncContainer()的源代码:

//将本地文件夹同步到容器
专用布尔同步容器(BlobTask任务)
{
尝试
{
列表blobList;
Dictionary blobDict=新字典();
//枚举容器中的blob。
if(BlobHelper.ListBlobs(容器,out blobList))
{
//把blob放在字典里,这样我们就可以很容易地按名字查找它。
foreach(blobList中的CloudBlob blob)
{
添加(blob.Name,blob);
}
//枚举watch文件夹中的文件-上载存储中没有相应Blob的任何文件。
字符串文件名;
DirectoryInfo di=新的DirectoryInfo(FolderPath);
IEnumerable fileList=di.EnumerateFiles(“*”,SearchOption.AllDirectory);
foreach(文件列表中的文件信息fi)
{
fileName=fi.FullName.Remove(0,di.FullName.Length+1);
如果(!isPathSafe(fi.FullName))
持续
if(BlobHelper.doesBlobexist(文件名,容器))
{
信息(“[”+容器+“\\”+文件名+”]:已在blob存储中”);
}
其他的
{
警告(“[”+容器+“\\”+文件名+”]:未找到,正在添加上载任务”);
添加(新的BlobTask()
{
Action=“上传”,
BlobName=fileName,
ContainerName=容器,
FilePath=fi.FullName,
RemainingRetryCount=最大重试次数
});
}
}
//检查blob中的所有exess文件,然后将其删除
CloudBlobContainer容器=BlobHelper.BlobClient.GetContainerReference(容器);
BlobRequestOptions options=新的BlobRequestOptions();
options.UseFlatBlobListing=true;
IEnumerable blobs=container.ListBlobs(选项);
CloudBlob-cbBlob;
字符串模拟类型;
if(blobs.Count()>0)
{
int containerLength=container.Name.Length+2;
foreach(IListBlobItem blob在blob中)
{
if(blob是CloudBlob)
{
cbBlob=blob作为CloudBlob;
fileName=cbBlob.Name;
string filePath=string.Concat(di.FullName,\\\,文件名);
mimeType=BlobHelper.getFileMimeTypeFromPath(filePath);
cbBlob.FetchAttributes();
//如有必要,设置缓存控制标头
if(cbBlob.Properties.CacheControl!=BlobHelper.blobCacheHeader)
{
cbBlob.Properties.CacheControl=BlobHelper.blobCacheHeader;
}
if(cbBlob.Properties.ContentType!=mimeType)
{
cbBlob.Properties.ContentType=mimeType;
}
cbBlob.SetProperties();
如果(!File.Exists(filePath)| |!isPathSafe(filePath))
{
警告(“[”+容器+“\\”+文件名+”]:在系统中找不到,但在blob中找到,正在添加删除任务”);
添加(新的BlobTask()
{
Action=“删除”,
BlobName=fileName,
ContainerName=容器,
FilePath=FilePath
});
}
}
}
}
返回true;
}
返回false;
}
捕获(例外情况除外)
{
if(ex是System.IO.PathTooLongException)
{
System.IO.PathTooLongException=ex作为PathTooLongException;
错误(exeption.ToString());
}
其他的
{
错误(例如ToString());
}
返回false;
}
}
私有bool-isPathSafe(字符串路径)
{
//检查文件是否隐藏,如果隐藏,请不要上载
if((File.GetAttributes(path)&FileAttributes.Hidden)=FileAttributes.Hidden)
返回false;
//检查路径中是否有任何文件夹被隐藏
FileInfo fi=新的FileInfo(路径);
if(isAnyPathDirHidden(fi.Directory))
返回false;
//检查该文件是否为异常文件之一,如果是,请不要上载。
return!Regex.IsMatch(path,regexfileexoption,RegexOptions.IgnoreCase | RegexOptions.Singleline);
}
/// 
///检查文件夹的路径文件夹是否隐藏。
/// 
///当前选中文件夹的DirectoryInfo
///如果文件夹隐藏,则为TRUE;如果未隐藏,则为FALSE
私有布尔isAnyPathDirHidden(目录信息目录)
{
如果(dir.Parent==nu
System.IO.PathTooLongException: The specified path, file name, or both are too long. The fully qualified file name must be less than 260 characters, and the directory name must be less than 248 characters.
   at System.IO.PathHelper.GetFullPathName()
   at System.IO.Path.NormalizePath(String path, Boolean fullCheck, Int32 maxPathLength, Boolean expandShortPaths)
   at System.Security.Util.StringExpressionSet.CanonicalizePath(String path, Boolean needFullPath)
   at System.Security.Util.StringExpressionSet.CreateListFromExpressions(String[] str, Boolean needFullPath)
   at System.Security.Permissions.FileIOPermission.AddPathList(FileIOPermissionAccess access, AccessControlActions control, String[] pathListOrig, Boolean checkForDuplicates, Boolean needFullPath, Boolean copyPathList)
   at System.IO.FileSystemInfo.get_FullName()
   at Neudesic.BlobDrop.BlobDrop.SyncContainer(BlobTask task)
// Sync local folder to container
private bool SyncContainer(BlobTask task)
{
    try
    {
        List<CloudBlob> blobList;
        Dictionary<string, CloudBlob> blobDict = new Dictionary<string,CloudBlob>();

        // Enumerate blobs in container.

        if (BlobHelper.ListBlobs(Container, out blobList))
        {
            // Put blob in a dictionary so we can easily look it up by name.
            foreach (CloudBlob blob in blobList)
            {
                blobDict.Add(blob.Name, blob);
            }

            // Enumerate the files in the watch folder - upload any files that do not yet have corresponding blobs in storage.
            string fileName;
            DirectoryInfo di = new DirectoryInfo(FolderPath);
            IEnumerable<FileInfo> fileList = di.EnumerateFiles("*", SearchOption.AllDirectories);
            foreach (FileInfo fi in fileList)
            {
                fileName = fi.FullName.Remove(0, di.FullName.Length + 1);
                if (!isPathSafe(fi.FullName))
                    continue;

                if (BlobHelper.doesTheBlobExist(fileName, Container))
                {
                    Info("  [" + Container + "\\" + fileName + "]: already in blob storage");
                }
                else
                {
                    Warning("  [" + Container + "\\" + fileName + "]: not found, adding upload task");

                    BlobQueue.Add(new BlobTask()
                    {
                        Action = "upload",
                        BlobName = fileName,
                        ContainerName = Container,
                        FilePath = fi.FullName,
                        RemainingRetryCount = MAX_RETRY_COUNT
                    });
                }
            }


            //checks the blob for all exess files in the blob and then removes them
            CloudBlobContainer container = BlobHelper.BlobClient.GetContainerReference(Container);
            BlobRequestOptions options = new BlobRequestOptions();
            options.UseFlatBlobListing = true;
            IEnumerable<IListBlobItem> blobs = container.ListBlobs(options);
            CloudBlob cbBlob;
            string mimeType;

            if (blobs.Count() > 0)
            {
                int containerLength = container.Name.Length + 2;
                foreach (IListBlobItem blob in blobs)
                {
                    if (blob is CloudBlob)
                    {
                        cbBlob = blob as CloudBlob;
                        fileName = cbBlob.Name;
                        string filePath = String.Concat(di.FullName, '\\', fileName);

                        mimeType = BlobHelper.getFileMimeTypeFromPath(filePath);
                        cbBlob.FetchAttributes();
                        // set cache-control header if necessary
                        if (cbBlob.Properties.CacheControl != BlobHelper.blobCacheHeader)
                        {
                            cbBlob.Properties.CacheControl = BlobHelper.blobCacheHeader;
                        }
                        if (cbBlob.Properties.ContentType != mimeType)
                        {
                            cbBlob.Properties.ContentType = mimeType;
                        }
                        cbBlob.SetProperties();

                        if (!File.Exists(filePath) || !isPathSafe(filePath))
                        {
                            Warning("  [" + Container + "\\" + fileName + "]: not found in system, but found in blob, adding deletion task");

                            BlobQueue.Add(new BlobTask()
                            {
                                Action = "delete",
                                BlobName = fileName,
                                ContainerName = Container,
                                FilePath = filePath
                            });
                        }
                    }
                }
            }

            return true;
        }
        return false;
    }
    catch (Exception ex)
    {
        if (ex is System.IO.PathTooLongException)
        {
            System.IO.PathTooLongException exeption = ex as PathTooLongException;
            Error(exeption.ToString());
        }
        else 
        {
            Error(ex.ToString());
        }

        return false;
    }
}


private bool isPathSafe(string path)
{
    //checks to see if the file is hidden or not, if so do not upload
    if ((File.GetAttributes(path) & FileAttributes.Hidden) == FileAttributes.Hidden)
        return false;

    //Checks to see if any of the folders in the path are hidden
    FileInfo fi = new FileInfo(path);
    if (isAnyPathDirHidden(fi.Directory))
        return false;

    //check to see if the file is one of the exception files, if so do not upload.
    return !Regex.IsMatch(path, regexFileExeption, RegexOptions.IgnoreCase | RegexOptions.Singleline);
}

/// <summary>
/// Checks to see if any of the folder's path folders are hidden or not.
/// </summary>
/// <param name="dir">The DirectoryInfo for the currently checked folder</param>
/// <returns>TRUE if the folder is hidden and FALSE if not</returns>
private bool isAnyPathDirHidden(DirectoryInfo dir)
{
    if (dir.Parent == null)
        return false;
    if ((File.GetAttributes(dir.FullName) & FileAttributes.Hidden) == FileAttributes.Hidden)
        return true;
    return isAnyPathDirHidden(dir.Parent);
}

// Upload a local file as a blob.
// Result: 0=success, 1=failed, retry scheduled, 2=failed

private int UploadBlob(BlobTask task)
{
    try
    {
        if (!File.Exists(task.FilePath))
        {
            Warning("   [" + task.BlobName + "]: file not found");
            return 2;
        }

        if (IsFileInUse(task.FilePath))
        {
            Warning("   [" + task.BlobName + "]: file in use");
            task.RemainingRetryCount--;
            if (task.RemainingRetryCount > 0)
            {
                Thread.Sleep(RETRY_SLEEP_INTERVAL);
                lock (BlobQueue)
                {
                    BlobQueue.Add(task);
                }
                return 1;
            }
            return 2;
        }

        if (BlobHelper.PutFileToBlob(task.FilePath, task.ContainerName, task.BlobName))
        {
            return 0;
        }
        else
        {
            return 1;
        }
    }

    // Failed to upload due to a storage service problem.

    catch(StorageException ex)
    {
        Error(ex.ToString());
        Warning("   [" + task.BlobName + "]: storage error");
        task.RemainingRetryCount--;
        if (task.RemainingRetryCount > 0)
        {
            Thread.Sleep(RETRY_SLEEP_INTERVAL);
            lock (BlobQueue)
            {
                BlobQueue.Add(task);
            }
            return 1;
        }
        return 2;
    }

    // Failed to upload due to a file access problem.

    catch (IOException ex)
    {
        Error(ex.ToString());
        Warning("   [" + task.BlobName + "]: could not access file");
        task.RemainingRetryCount--;
        if (task.RemainingRetryCount > 0)
        {
            Thread.Sleep(RETRY_SLEEP_INTERVAL);
            lock (BlobQueue)
            {
                BlobQueue.Add(task);
            }
            return 1;
        }
        return 2;
    }
    catch (Exception ex)
    {
        Error(ex.ToString());
        return 2;
    }
}


// Delete a blob.

private bool DeleteBlob(BlobTask task)
{
    bool ret;
    if (BlobHelper.doesTheBlobExist(task.BlobName, Container))
    {
        ret = DeleteSingleBlob(task.ContainerName, task.BlobName);
    }
    else
    {
        //checks to see if the deletion task is a folder
        //the way it is checked if the virtual folder exists is to check for all subitems (even in subfolders) and then removed all found-
        ret = true;

        CloudBlobContainer container = BlobHelper.BlobClient.GetContainerReference(Container);
        CloudBlobDirectory test = container.GetDirectoryReference(task.BlobName);
        BlobRequestOptions options = new BlobRequestOptions();
        options.UseFlatBlobListing = true;
        IEnumerable<IListBlobItem> blobs = test.ListBlobs(options);
        if (blobs.Count() > 0)
        {
            foreach (IListBlobItem blob in blobs)
            {
                if (blob is CloudBlob)
                {
                    if (!DeleteSingleBlob(task.ContainerName, (blob as CloudBlob).Name))
                    {
                        ret = false;
                    }
                }
            }
        }
    }

    return ret;
}


private bool DeleteSingleBlob(string containerName, string blobName)
{
    try
    {
        return BlobHelper.DeleteBlob(containerName, blobName);
    }
    catch (Exception ex)
    {
        Error(ex.ToString());
        return false;
    }
}