Ejemplo n.º 1
0
        /// <summary>
        /// 根据文件大小创建文件。
        /// 注意:多个用户同时上传相同文件时,可能会同时创建相同文件。
        /// </summary>
        public void make(string filePath, long len)
        {
            //文件不存在则创建
            if (string.IsNullOrEmpty(filePath))
            {
                return;
            }
            if (!LongPathFile.Exists(filePath))
            {
                var pos = filePath.LastIndexOf('\\');
                if (-1 == pos)
                {
                    pos = filePath.LastIndexOf('/');
                }
                var dir = filePath.Substring(0, pos);
                //自动创建目录
                if (!LongPathDirectory.Exists(dir))
                {
                    System.Diagnostics.Debug.WriteLine(string.Format("路径不存在:{0}", dir));
                    PathTool.createDirectory(dir);
                }
                else
                {
                    System.Diagnostics.Debug.WriteLine(string.Format("路径存在:{0}", dir));
                }

                var fs = LongPathFile.Open(filePath, FileMode.Create, FileAccess.Write);
                fs.SetLength(len);
                fs.Close();
            }
        }
Ejemplo n.º 2
0
        public static bool Exists(string path)
        {
#if DOTNET5_4
            return(Directory.Exists(path));
#else
            return(LongPathDirectory.Exists(path));
#endif
        }
Ejemplo n.º 3
0
 public static bool Exists(string path)
 {
     if (path.Length < MAX_PATH)
     {
         return(System.IO.Directory.Exists(path));
     }
     else
     {
         return(LongPathDirectory.Exists(path));
     }
 }
        public static bool Exists(string path)
        {
#if DOTNET5_4
            return(Directory.Exists(path));
#else
            if (DMLibTestConstants.SupportUNCPath)
            {
                path = LongPath.ToUncPath(path);
            }
            return(LongPathDirectory.Exists(path));
#endif
        }
Ejemplo n.º 5
0
        /// <summary>
        ///     Determines whether the specified path exists and refers to a junction point.
        /// </summary>
        /// <param name = "path">The junction point path</param>
        /// <returns>True if the specified path represents a junction point</returns>
        /// <exception cref = "IOException">Thrown if the specified path is invalid
        ///     or some other error occurs</exception>
        public static bool Exists(Path path)
        {
            if (!LongPathDirectory.Exists(path))
            {
                return(false);
            }

            using (var handle = OpenReparsePoint(path, EFileAccess.GenericRead))
            {
                var target = InternalGetTarget(handle);
                return(target != null);
            }
        }
Ejemplo n.º 6
0
        private void OnFileSystemEntriesListBoxMouseDoubleClick(object sender, MouseEventArgs e)
        {
            if (fileSystemEntriesListBox.SelectedItem != null)
            {
                string path = (string)fileSystemEntriesListBox.SelectedItem;

                if (LongPathDirectory.Exists(path))
                {
                    this.currentPath.Text = path;
                }

                RefreshFileList();
            }
        }
Ejemplo n.º 7
0
        bool IDirectoryAdapter.Exists(string path)
        {
            AssertAllowed(path);

#if !MONO
            var mTx = CurrentTransaction();
            if (mTx.HasValue)
            {
                return(((IDirectoryAdapter)mTx.Value).Exists(path));
            }
#endif

            return(LongPathDirectory.Exists(path));
        }
Ejemplo n.º 8
0
        /// <summary>
        ///     Deletes a junction point at the specified source directory along with the directory itself.
        ///     Does nothing if the junction point does not exist.
        /// </summary>
        /// <remarks>
        ///     Only works on NTFS.
        /// </remarks>
        /// <param name = "junctionPoint">The junction point path</param>
        public static void Delete(Path junctionPoint)
        {
            if (!LongPathDirectory.Exists(junctionPoint))
            {
                if (LongPathFile.Exists(junctionPoint))
                {
                    throw new IOException("Path is not a junction point.");
                }

                return;
            }

            using (var handle = OpenReparsePoint(junctionPoint, EFileAccess.GenericWrite))
            {
                var reparseDataBuffer = new REPARSE_DATA_BUFFER();

                reparseDataBuffer.ReparseTag        = IO_REPARSE_TAG_MOUNT_POINT;
                reparseDataBuffer.ReparseDataLength = 0;
                reparseDataBuffer.PathBuffer        = new byte[0x3ff0];

                var inBufferSize = Marshal.SizeOf(reparseDataBuffer);
                var inBuffer     = Marshal.AllocHGlobal(inBufferSize);
                try
                {
                    Marshal.StructureToPtr(reparseDataBuffer, inBuffer, false);

                    int bytesReturned;
                    var result = DeviceIoControl(handle.DangerousGetHandle(), FSCTL_DELETE_REPARSE_POINT,
                                                 inBuffer, 8, IntPtr.Zero, 0, out bytesReturned, IntPtr.Zero);

                    if (!result)
                    {
                        ThrowLastWin32Error("Unable to delete junction point.");
                    }
                }
                finally
                {
                    Marshal.FreeHGlobal(inBuffer);
                }

                try
                {
                    LongPathDirectory.Delete(junctionPoint);
                }
                catch (IOException ex)
                {
                    throw new IOException("Unable to delete junction point.", ex);
                }
            }
        }
Ejemplo n.º 9
0
        /// <summary>
        /// 自动创建多层级路径
        /// </summary>
        /// <param name="path"></param>
        /// <param name="separator">路径分隔符,默认:/</param>
        public static void createDirectory(string path, char separator = '/')
        {
            var dirs   = path.Split(separator);
            var folder = "";

            foreach (var dir in dirs)
            {
                if (folder != "")
                {
                    folder = folder + "/" + dir;
                }
                else
                {
                    folder = dir;
                }
                if (!LongPathDirectory.Exists(folder))
                {
                    LongPathDirectory.Create(folder);
                }
                System.Diagnostics.Debug.WriteLine(folder);
            }
        }
Ejemplo n.º 10
0
        private void OnDeleteButtonClick(object sender, EventArgs e)
        {
            string selectedPath = (string)fileSystemEntriesListBox.SelectedItem;

            try {
                if (LongPathDirectory.Exists(selectedPath))
                {
                    LongPathDirectory.Delete(selectedPath);
                }
                else
                {
                    LongPathFile.Delete(selectedPath);
                }
            }
            catch (IOException ex) {
                ShowError(ex);
            }
            catch (UnauthorizedAccessException ex) {
                ShowError(ex);
            }

            RefreshFileList();
        }
Ejemplo n.º 11
0
        public static IEnumerable <string> EnumerateFiles(
            string path,
            string searchPattern,
            string fromFilePath,
            SearchOption searchOption,
            bool followsymlink,
            CancellationToken cancellationToken)
        {
            Utils.CheckCancellation(cancellationToken);

            if ((searchOption != SearchOption.TopDirectoryOnly) && (searchOption != SearchOption.AllDirectories))
            {
                throw new ArgumentOutOfRangeException("searchOption");
            }

            // Remove whitespaces in the end.
            searchPattern = searchPattern.TrimEnd();
            if (searchPattern.Length == 0)
            {
                // Returns an empty string collection.
                return(new List <string>());
            }

            // To support patterns like "folderA\" aiming at listing files under some folder.
            if ("." == searchPattern)
            {
                searchPattern = "*";
            }

            Utils.CheckCancellation(cancellationToken);

            CheckSearchPattern(searchPattern);

            Utils.CheckCancellation(cancellationToken);

            // Check path permissions.
            string fullPath = null;

            if (Interop.CrossPlatformHelpers.IsWindows)
            {
                fullPath = LongPath.ToUncPath(path);
            }
            else
            {
                fullPath = Path.GetFullPath(path);
            }
#if CODE_ACCESS_SECURITY
            CheckPathDiscoveryPermission(fullPath);
#endif // CODE_ACCESS_SECURITY

            string patternDirectory = LongPath.GetDirectoryName(searchPattern);
#if CODE_ACCESS_SECURITY
            if (!string.IsNullOrEmpty(patternDirectory))
            {
                CheckPathDiscoveryPermission(LongPath.Combine(fullPath, patternDirectory));
            }
#endif // CODE_ACCESS_SECURITY

            if (!string.IsNullOrEmpty(fromFilePath) &&
                !string.IsNullOrEmpty(patternDirectory))
            {
                // if file pattern is like folder\fileName*, we'll list location\folder with pattern fileName*
                // but the listted relative path will still be like folder\fileName1, and the continuation token will look the same.
                // Then here we need to make continuation token to be path relative to location\folder.
                string tmpPatternDir = AppendDirectorySeparator(patternDirectory);
                fromFilePath = fromFilePath.Substring(tmpPatternDir.Length);
            }

            string fullPathWithPattern = LongPath.Combine(fullPath, searchPattern);

            // To support patterns like "folderA\" aiming at listing files under some folder.
            char lastC = fullPathWithPattern[fullPathWithPattern.Length - 1];
            if (Path.DirectorySeparatorChar == lastC ||
                Path.AltDirectorySeparatorChar == lastC ||
                Path.VolumeSeparatorChar == lastC)
            {
                fullPathWithPattern = fullPathWithPattern + '*';
            }

            string directoryName = AppendDirectorySeparator(LongPath.GetDirectoryName(fullPathWithPattern));
            string filePattern   = fullPathWithPattern.Substring(directoryName.Length);

            if (!LongPathDirectory.Exists(directoryName))
            {
                throw new DirectoryNotFoundException(
                          string.Format(
                              CultureInfo.CurrentCulture,
                              Resources.PathNotFound,
                              directoryName));
            }

            Utils.CheckCancellation(cancellationToken);
            return(InternalEnumerateFiles(directoryName, filePattern, fromFilePath, searchOption, followsymlink, cancellationToken));
        }
Ejemplo n.º 12
0
        private static IEnumerable <string> InternalEnumerateFiles(
            string directoryName,
            string filePattern,
            string fromFilePath,
            SearchOption searchOption,
            bool followsymlink,
            CancellationToken cancellationToken)
        {
            Stack <string> folders = new Stack <string>();
            Stack <string> currentFolderSubFolders = new Stack <string>();

            folders.Push(directoryName);

            string[] pathSegList             = null;
            bool     passedContinuationToken = false;
            int      pathSegListIndex        = 0;

            if (null != fromFilePath)
            {
                pathSegList = fromFilePath.Split(new char[] { Path.DirectorySeparatorChar });
            }
            else
            {
                passedContinuationToken = true;
            }

            while (folders.Count > 0)
            {
                string folder = AppendDirectorySeparator(folders.Pop());

                Utils.CheckCancellation(cancellationToken);

                // Skip non-existent folders
                if (!LongPathDirectory.Exists(folder))
                {
#if DOTNET5_4
                    if (CrossPlatformHelpers.IsLinux)
                    {
                        if (!SymlinkedDirExists(folder))
                        {
                            continue;
                        }
                    }
                    else
                    {
                        continue;
                    }
#else
                    continue;
#endif
                }

#if CODE_ACCESS_SECURITY // Only accessible to fully trusted code in non-CAS models
                try
                {
                    CheckPathDiscoveryPermission(folder);
                }
                catch (SecurityException)
                {
                    // Ignore this folder if we have no right to discovery it.
                    continue;
                }
                catch (UnauthorizedAccessException)
                {
                    // Ignore this folder if we have no right to discovery it.
                    continue;
                }
#else // CODE_ACCESS_SECURITY
                try
                {
                    // In non-CAS scenarios, it's still important to check for folder accessibility
                    // since the OS can block access to some paths. Getting files from a location
                    // will force path discovery checks which will indicate whether or not the user
                    // is authorized to access the directory.
                    foreach (var fileItem in LongPathDirectory.EnumerateFileSystemEntries(folder, "*", SearchOption.TopDirectoryOnly))
                    {
                        // Just try to get the first item in directly to check whether has permission to access the directory.
                        break;
                    }
                }
                catch (SecurityException)
                {
                    // Ignore this folder if we have no right to discovery it.
                    continue;
                }
                catch (UnauthorizedAccessException)
                {
                    // Ignore this folder if we have no right to discovery it.
                    continue;
                }
                catch (Exception ex)
                {
                    throw new TransferException(string.Format(CultureInfo.CurrentCulture, Resources.EnumerateDirectoryException, folder), ex);
                }
#endif // CODE_ACCESS_SECURITY

                // Return all files contained directly in this folder (which occur after the continuationTokenFile)
                // Only consider the folder if the continuation token is already past or the continuation token may be passed by
                // a file within this directory (based on pathSegListIndex and the patSegList.Length)
                if (passedContinuationToken ||
                    (pathSegList.Length - 1 == pathSegListIndex))
                {
                    string continuationTokenFile = null;

                    if (!passedContinuationToken)
                    {
                        continuationTokenFile = pathSegList[pathSegListIndex];
                    }

                    // Load files directly under this folder.
                    foreach (var filePath in Utils.CatchException(() =>
                    {
                        return(LongPathDirectory.EnumerateFileSystemEntries(folder, filePattern, SearchOption.TopDirectoryOnly));
                    },
                                                                  (ex) =>
                    {
                        throw new TransferException(string.Format(CultureInfo.CurrentCulture, Resources.EnumerateDirectoryException, folder), ex);
                    }))
                    {
                        Utils.CheckCancellation(cancellationToken);

                        EnumerateFileEntryInfo fileEntryInfo = null;

                        try
                        {
#if DOTNET5_4
                            if (CrossPlatformHelpers.IsLinux)
                            {
                                fileEntryInfo = GetFileEntryInfo(filePath);
                            }
                            else
                            {
                                fileEntryInfo = new EnumerateFileEntryInfo()
                                {
                                    FileName       = LongPath.GetFileName(filePath),
                                    FileAttributes = LongPathFile.GetAttributes(filePath)
                                };
                            }
#else
                            fileEntryInfo = new EnumerateFileEntryInfo()
                            {
                                FileName       = LongPath.GetFileName(filePath),
                                FileAttributes = LongPathFile.GetAttributes(filePath)
                            };
#endif
                        }
                        // Cross-plat file system accessibility settings may cause exceptions while
                        // retrieving attributes from inaccessible paths. These paths shold be skipped.
                        catch (FileNotFoundException) { }
                        catch (IOException) { }
                        catch (UnauthorizedAccessException) { }
                        catch (Exception ex)
                        {
                            throw new TransferException(string.Format(CultureInfo.CurrentCulture, Resources.FailedToGetFileInfoException, filePath), ex);
                        }

                        if (null == fileEntryInfo)
                        {
                            continue;
                        }

                        if (FileAttributes.Directory != (fileEntryInfo.FileAttributes & FileAttributes.Directory))
                        {
                            if (passedContinuationToken)
                            {
                                yield return(LongPath.Combine(folder, fileEntryInfo.FileName));
                            }
                            else
                            {
                                if (CrossPlatformHelpers.IsLinux)
                                {
                                    if (!passedContinuationToken)
                                    {
                                        if (string.Equals(fileEntryInfo.FileName, continuationTokenFile, StringComparison.Ordinal))
                                        {
                                            passedContinuationToken = true;
                                        }
                                    }
                                    else
                                    {
                                        yield return(LongPath.Combine(folder, fileEntryInfo.FileName));
                                    }
                                }
                                else
                                {
                                    // Windows file system is case-insensitive; OSX and Linux are case-sensitive
                                    var comparison    = CrossPlatformHelpers.IsWindows ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal;
                                    int compareResult = string.Compare(fileEntryInfo.FileName, continuationTokenFile, comparison);
                                    if (compareResult < 0)
                                    {
                                        // Skip files prior to the continuation token file
                                        continue;
                                    }

                                    passedContinuationToken = true;

                                    if (compareResult > 0)
                                    {
                                        yield return(LongPath.Combine(folder, fileEntryInfo.FileName));
                                    }
                                }
                            }
                        }
                    }

                    // Passed folder which continuation token file is under,
                    // set passedContinuationToken to true.
                    passedContinuationToken = true;
                }

                // Next add sub-folders for processing
                if (SearchOption.AllDirectories == searchOption)
                {
                    string fromSubfolder  = null;
                    bool   passedSubfoler = passedContinuationToken;
                    if (!passedContinuationToken)
                    {
                        fromSubfolder = pathSegList[pathSegListIndex];
                        pathSegListIndex++;
                    }

                    // Add sub-folders.
                    foreach (var filePath in Utils.CatchException(() =>
                    {
                        return(LongPathDirectory.EnumerateFileSystemEntries(folder, "*", SearchOption.TopDirectoryOnly));
                    },
                                                                  (ex) =>
                    {
                        throw new TransferException(string.Format(CultureInfo.CurrentCulture, Resources.EnumerateDirectoryException, folder), ex);
                    }))
                    {
                        Utils.CheckCancellation(cancellationToken);

                        EnumerateFileEntryInfo fileEntryInfo = null;

                        try
                        {
                            if (CrossPlatformHelpers.IsLinux)
                            {
                                fileEntryInfo = GetFileEntryInfo(filePath);
                            }
                            else
                            {
                                fileEntryInfo = new EnumerateFileEntryInfo()
                                {
                                    FileName       = LongPath.GetFileName(filePath),
                                    FileAttributes = LongPathFile.GetAttributes(filePath)
                                };
                            }
                        }
                        // Cross-plat file system accessibility settings may cause exceptions while
                        // retrieving attributes from inaccessible paths. These paths shold be skipped.
                        catch (FileNotFoundException) { }
                        catch (IOException) { }
                        catch (UnauthorizedAccessException) { }
                        catch (Exception ex)
                        {
                            throw new TransferException(string.Format(CultureInfo.CurrentCulture, Resources.FailedToGetFileInfoException, filePath), ex);
                        }

                        if (null == fileEntryInfo)
                        {
                            continue;
                        }

                        if (FileAttributes.Directory == (fileEntryInfo.FileAttributes & FileAttributes.Directory) &&
                            !fileEntryInfo.FileName.Equals(@".") &&
                            !fileEntryInfo.FileName.Equals(@".."))
                        {
                            bool toBeEnumerated = false;
                            if (CrossPlatformHelpers.IsLinux)
                            {
                                toBeEnumerated = ToEnumerateTheSubDir(LongPath.Combine(folder, fileEntryInfo.FileName), fileEntryInfo, followsymlink);
                            }
                            // TODO: Ignore junction point or not. Make it configurable.
                            else if (FileAttributes.ReparsePoint != (fileEntryInfo.FileAttributes & FileAttributes.ReparsePoint))
                            {
                                toBeEnumerated = true;
                            }

                            if (toBeEnumerated)
                            {
                                if (passedSubfoler)
                                {
                                    currentFolderSubFolders.Push(LongPath.Combine(folder, fileEntryInfo.FileName));
                                }
                                else
                                {
                                    if (CrossPlatformHelpers.IsLinux)
                                    {
                                        if (string.Equals(fileEntryInfo.FileName, fromSubfolder, StringComparison.Ordinal))
                                        {
                                            passedSubfoler = true;
                                            currentFolderSubFolders.Push(LongPath.Combine(folder, fileEntryInfo.FileName));
                                        }
                                    }
                                    else
                                    {
                                        // Windows file system is case-insensitive; OSX and Linux are case-sensitive
                                        var comparison    = CrossPlatformHelpers.IsWindows ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal;
                                        int compareResult = string.Compare(fileEntryInfo.FileName, fromSubfolder, comparison);

                                        if (compareResult >= 0)
                                        {
                                            passedSubfoler = true;
                                            currentFolderSubFolders.Push(LongPath.Combine(folder, fileEntryInfo.FileName));

                                            if (compareResult > 0)
                                            {
                                                passedContinuationToken = true;
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }

                    if (currentFolderSubFolders.Count <= 0)
                    {
                        passedContinuationToken = true;
                    }
                    else
                    {
                        while (currentFolderSubFolders.Count > 0)
                        {
                            folders.Push(currentFolderSubFolders.Pop());
                        }
                    }
                }
            }
        }
 public override bool DirectoryExists(string directoryPath)
 {
     return(LongPathDirectory.Exists(directoryPath));
 }