파일 경로가 너무 긴 예외를 해결하는 가장 좋은 방법
SP 사이트에서 모든 문서 라이브러리를 다운로드하는 앱을 만들었지 만 한 번에이 오류가 발생했습니다 (Google을 살펴 보았지만 아무것도 찾을 수 없었습니다. 이제이 문제를 해결하는 트릭을 아는 사람이 있으면 다른 방법으로 응답 해주세요. 그것을보고)
System.IO.PathTooLongException : 지정된 경로, 파일 이름 또는 둘 다 너무 깁니다. 완전한 파일 이름은 260 자 미만이어야하며 디렉토리 이름은 248 자 미만이어야합니다. System.IO.Path.NormalizePathFast (String path, Boolean fullCheck) at System.IO.Path.GetFullPathInternal (String path) at System.IO.FileStream.Init (String path, FileMode mode, FileAccess access, Int32 rights, Boolean useRights , FileShare share, Int32 bufferSize, FileOptions options, SECURITY_ATTRIBUTES secAttrs, String msgPath, Boolean bFromProxy) at System.IO.FileStream..ctor (String path, FileMode mode, FileAccess access, FileShare share, Int32 bufferSize, FileOptions options) at System. IO.File.Create (문자열 경로)
문자열 한도에 도달하면 코드는 아래와 같습니다.
#region Downloading Schemes
private void btnDownload_Click(object sender, EventArgs e)
{
TreeNode currentNode = tvWebs.SelectedNode;
SPObjectData objectData = (SPObjectData)currentNode.Tag;
try
{
CreateLoggingFile();
using (SPWeb TopLevelWeb = objectData.Web)
{
if(TopLevelWeb != null)
dwnEachWeb(TopLevelWeb, TopLevelWeb.Title, tbDirectory.Text);
}
}
catch (Exception ex)
{
Trace.WriteLine(string.Format("Exception caught when tried to pass TopLevelWeb:{1}, Title = {2}, object data to (dwnEachWeb_method), Exception: {0}", ex.ToString(), objectData.Web, objectData.Title));
}
finally
{
CloseLoggingFile();
}
}
private void dwnEachWeb(SPWeb TopLevelWeb, string FolderName, string CurrentDirectory)
{
if (TopLevelWeb != null)
{
if (TopLevelWeb.Webs != null)
{
CurrentDirectory = CurrentDirectory + "\\" + TopLevelWeb.Title;
CreateFolder(CurrentDirectory);
foreach (SPWeb ChildWeb in TopLevelWeb.Webs)
{
dwnEachWeb(ChildWeb, ChildWeb.Title, CurrentDirectory);
ChildWeb.Dispose();
}
dwnEachList(TopLevelWeb, CurrentDirectory);
//dwnEachList(TopLevelWeb, FolderName, CurrentDirectory);
}
}
}
private void dwnEachList(SPWeb oWeb, string CurrentDirectory)
{
foreach (SPList oList in oWeb.Lists)
{
if (oList is SPDocumentLibrary && !oList.Hidden)
{
dwnEachFile(oList.RootFolder, CurrentDirectory);
}
}
}
private void dwnEachFile(SPFolder oFolder, string CurrentDirectory)
{
if (oFolder.Files.Count != 0)
{
CurrentDirectory = CurrentDirectory + "\\" + oFolder.Name;
CreateFolder(CurrentDirectory);
foreach (SPFile ofile in oFolder.Files)
{
if (CreateDirectoryStructure(CurrentDirectory, ofile.Url))
{
var filepath = System.IO.Path.Combine(CurrentDirectory, ofile.Url);
byte[] binFile = ofile.OpenBinary();
System.IO.FileStream fstream = System.IO.File.Create(filepath);
fstream.Write(binFile, 0, binFile.Length);
fstream.Close();
}
}
}
}
//creating directory where files will be download
private bool CreateDirectoryStructure(string baseFolder, string filepath)
{
if (!Directory.Exists(baseFolder)) return false;
var paths = filepath.Split('/');
for (var i = 0; i < paths.Length - 1; i++)
{
baseFolder = System.IO.Path.Combine(baseFolder, paths[i]);
Directory.CreateDirectory(baseFolder);
}
return true;
}
//creating folders
private bool CreateFolder(string CurrentDirectory)
{
if (!Directory.Exists(CurrentDirectory))
{
Directory.CreateDirectory(CurrentDirectory);
}
return true;
}
//shorting string
#endregion
As the cause of the error is obvious, here's some information that should help you solve the problem:
See this MS article about Naming Files, Paths, and Namespaces
Here's a quote from the link:
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<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.)
And a few workarounds (taken from the comments):
There are ways to solve the various problems. The basic idea of the solutions listed below is always the same: Reduce the path-length in order to have path-length + name-length < MAX_PATH
. You may:
- Share a subfolder
- Use the commandline to assign a drive letter by means of SUBST
- Use AddConnection under VB to assign a drive letter to a path
There's a library called Zeta Long Paths that provides a .NET API to work with long paths.
Here's a good article that covers this issue for both .NET and PowerShell: ".NET, PowerShell Path too Long Exception and a .NET PowerShell Robocopy Clone"
The solution that worked for me was to edit the registry key to enable long path behaviour, setting the value to 1. This is a new opt-in feature for Windows 10
HKLM\SYSTEM\CurrentControlSet\Control\FileSystem LongPathsEnabled (Type: REG_DWORD)
I got this solution from a named section of the article that @james-hill posted.
https://docs.microsoft.com/windows/desktop/FileIO/naming-a-file#maximum-path-length-limitation
On Windows 8.1, using. NET 3.5, I had a similar problem.
Although the name of my file was only 239 characters length when I went to instantiate a FileInfo object with just the file name (without path) occurred an exception of type System. IO.PathTooLongException
2014-01-22 11:10:35 DEBUG LogicalDOCOutlookAddIn.LogicalDOCAddIn - fileName.Length: 239
2014-01-22 11:10:35 ERROR LogicalDOCOutlookAddIn.LogicalDOCAddIn - Exception in ImportEmail System.IO.PathTooLongException: Percorso e/o nome di file specificato troppo lungo. Il nome di file completo deve contenere meno di 260 caratteri, mentre il nome di directory deve contenere meno di 248 caratteri.
in System.IO.Path.NormalizePathFast(String path, Boolean fullCheck)
in System.IO.FileInfo..ctor(String fileName)
in LogicalDOCOutlookAddIn.LogicalDOCAddIn.GetTempFilePath(String fileName) in C:\Users\alle\Documents\Visual Studio 2010\Projects\MyAddin1Outlook20072010\MyAddin1Outlook20072010\LogicalDOCAddIn.cs:riga 692
in LogicalDOCOutlookAddIn.LogicalDOCAddIn.ImportEmail(_MailItem mailItem, OutlookConfigXML configXML, Int64 targetFolderID, String SID) in C:\Users\alle\Documents\Visual Studio 2010\Projects\MyAddin1Outlook20072010\MyAddin1Outlook20072010\LogicalDOCAddIn.cs:riga 857
in LogicalDOCOutlookAddIn.LogicalDOCAddIn.ImportEmails(Explorers explorers, OutlookConfigXML configXML, Int64 targetFolderID, Boolean suppressResultMB) in C:\Users\alle\Documents\Visual Studio 2010\Projects\MyAddin1Outlook20072010\MyAddin1Outlook20072010\LogicalDOCAddIn.cs:riga 99
I resolved the problem trimming the file name to 204 characters (extension included).
You can create a symbolic link with a shorter directory. First open command line for example by Shift + RightClick
in your desired folder with a shorter path (you may have to run it as administrator).
Then type with relative or absolute paths:
mklink ShortPath\To\YourLinkedSolution C:\Path\To\Your\Solution /D
And then start the Solution from the shorter path. The advantage here is: You don't have to move anything.
If you are having an issue with your bin files due to a long path, In Visual Studio 2015 you can go to the offending project's property page and change the relative Output Directory to a shorter one.
E.g. bin\debug\ becomes C:\_bins\MyProject\
What worked for me is moving my project as it was on the desktop (C:\Users\lachezar.l\Desktop\MyFolder) to (C:\0\MyFolder) which as you can see uses shorter path and reducing it solved the problem.
From my experience, won't recommend my below answer for any public facing Web applications.
If you need it for your inhouse tools or for Testing, I would recommend to share it on your own machine.
-Right click on the root path you need to access
-Choose Properties
-Click on Share button and add your chosen users who can access it
This will then create a shared directory like \\{PCName}\{YourSharedRootDirectory} This could be definitely much less than your full path I hope, for me I could reduce to 30 characters from about 290 characters. :)
Not mention so far and an update, there is a very well establish library for handling paths that are too long. AlphaFS is a .NET library providing more complete Win32 file system functionality to the .NET platform than the standard System.IO classes. The most notable deficiency of the standard .NET System.IO is the lack of support of advanced NTFS features, most notably extended length path support (eg. file/directory paths longer than 260 characters).
The best answer I can find, is in one of the comments here. Adding it to the answer so that someone won't miss the comment and should definitely try this out. It fixed the issue for me.
We need to map the solution folder to a drive using the "subst" command in command prompt- e.g., subst z:
And then open the solution from this drive (z in this case). This would shorten the path as much as possible and could solve the lengthy filename issue.
You can reduce the project name in:
Solution Properties -> Application -> Assembly Name
참고URL : https://stackoverflow.com/questions/8745215/best-way-to-resolve-file-path-too-long-exception
'program story' 카테고리의 다른 글
rsync와 양방향 동기화 (0) | 2020.09.06 |
---|---|
NuGet 패키지에 클래스 라이브러리 용 Xml 문서를 어떻게 포함하나요? (0) | 2020.09.06 |
어떤 Java FTP 클라이언트 라이브러리를 사용해야합니까? (0) | 2020.09.06 |
일하는 사람을위한 결합 자 설명 (0) | 2020.09.06 |
'할당 분기 조건 크기가 너무 큼'은 무엇을 의미하며 어떻게 해결합니까? (0) | 2020.09.06 |