public override void DeleteFile(string filePath)
 {
     LongPathFile.Delete(filePath);
 }
 public override bool FileExists(string filePath)
 {
     return(LongPathFile.Exists(filePath));
 }
 public override FileStream OpenFile(string filePath)
 {
     return(LongPathFile.Open(filePath, FileMode.OpenOrCreate, FileAccess.ReadWrite));
 }
        private async Task OpenInputStreamAsync()
        {
            Debug.Assert(
                State.OpenInputStream == this.state,
                "OpenInputStreamAsync called, but state is not OpenInputStream.");

            if (Interlocked.CompareExchange(ref workToken, 0, 1) == 0)
            {
                return;
            }

            await Task.Yield();

            this.NotifyStarting();
            this.Controller.CheckCancellation();

            if (this.transferJob.Source.Type == TransferLocationType.Stream)
            {
                StreamLocation streamLocation = this.transferJob.Source as StreamLocation;
                this.inputStream = streamLocation.Stream;
                this.ownsStream  = false;

                if (!this.inputStream.CanRead)
                {
                    throw new NotSupportedException(string.Format(
                                                        CultureInfo.CurrentCulture,
                                                        Resources.StreamMustSupportReadException,
                                                        "inputStream"));
                }
            }
            else
            {
                FileLocation fileLocation = this.transferJob.Source as FileLocation;
                Debug.Assert(
                    null != fileLocation,
                    "Initializing StreamedReader instance, but source is neither a stream nor a file");

                try
                {
                    if (fileLocation.RelativePath != null &&
                        fileLocation.RelativePath.Length > Constants.MaxRelativePathLength)
                    {
                        string errorMessage = string.Format(
                            CultureInfo.CurrentCulture,
                            Resources.RelativePathTooLong,
                            fileLocation.RelativePath);
                        throw new TransferException(TransferErrorCode.OpenFileFailed, errorMessage);
                    }
#if DOTNET5_4
                    string filePath = fileLocation.FilePath;
                    if (Interop.CrossPlatformHelpers.IsWindows)
                    {
                        filePath = LongPath.ToUncPath(fileLocation.FilePath);
                    }
                    // Attempt to open the file first so that we throw an exception before getting into the async work
                    this.inputStream = new FileStream(
                        filePath,
                        FileMode.Open,
                        FileAccess.Read,
                        FileShare.Read);
#else
                    this.inputStream = LongPathFile.Open(
                        fileLocation.FilePath,
                        FileMode.Open,
                        FileAccess.Read,
                        FileShare.Read);
#endif
                    this.ownsStream = true;
                }
                catch (Exception ex)
                {
                    if ((ex is NotSupportedException) ||
                        (ex is IOException) ||
                        (ex is UnauthorizedAccessException) ||
                        (ex is SecurityException) ||
                        (ex is ArgumentException && !(ex is ArgumentNullException)))
                    {
                        string exceptionMessage = string.Format(
                            CultureInfo.CurrentCulture,
                            Resources.FailedToOpenFileException,
                            fileLocation.FilePath,
                            ex.Message);

                        throw new TransferException(
                                  TransferErrorCode.OpenFileFailed,
                                  exceptionMessage,
                                  ex);
                    }
                    else
                    {
                        throw;
                    }
                }
            }

            try
            {
                this.SharedTransferData.TotalLength = this.inputStream.Length;
            }
            catch (NotSupportedException)
            {
                this.SharedTransferData.TotalLength = -1;
            }

            // Only do calculation related to transfer window when the file contains multiple chunks.
            if (!this.EnableOneChunkFileOptimization)
            {
                var checkpoint = this.transferJob.CheckPoint;

                checkpoint.TransferWindow.Sort();

                this.readLength = checkpoint.EntryTransferOffset;

                if (checkpoint.TransferWindow.Any())
                {
                    // The size of last block can be smaller than BlockSize.
                    this.readLength -= Math.Min(checkpoint.EntryTransferOffset - checkpoint.TransferWindow.Last(), this.SharedTransferData.BlockSize);
                    this.readLength -= (checkpoint.TransferWindow.Count - 1) * this.SharedTransferData.BlockSize;
                }

                if (this.readLength < 0)
                {
                    throw new InvalidOperationException(Resources.RestartableInfoCorruptedException);
                }
                else if ((checkpoint.EntryTransferOffset > 0) && (!this.inputStream.CanSeek))
                {
                    throw new NotSupportedException(string.Format(
                                                        CultureInfo.CurrentCulture,
                                                        Resources.StreamMustSupportSeekException,
                                                        "inputStream"));
                }

                this.lastTransferWindow = new Queue <long>(this.transferJob.CheckPoint.TransferWindow);
            }

            this.md5HashStream = new MD5HashStream(
                this.inputStream,
                this.transferJob.CheckPoint.EntryTransferOffset,
                true);

            this.PreProcessed = true;

            if (this.readLength != this.SharedTransferData.TotalLength)
            {
                // Change the state to 'ReadStream' before awaiting MD5 calculation task to not block the reader.
                this.state     = State.ReadStream;
                this.workToken = 1;
            }
            else
            {
                Interlocked.Exchange(ref this.readCompleted, 1);
            }

            if (!this.md5HashStream.FinishedSeparateMd5Calculator)
            {
                await Task.Run(() =>
                {
                    this.md5HashStream.CalculateMd5(this.Scheduler.MemoryManager, this.Controller.CheckCancellation);
                });
            }

            this.SetChunkFinish();
        }
Пример #5
0
        private async Task HandleOutputStreamAsync()
        {
            if (Interlocked.CompareExchange(ref workToken, 0, 1) == 0)
            {
                return;
            }

            await Task.Run(async() =>
            {
                // Only do calculation related to transfer window when the file contains multiple chunks.
                if (!this.EnableOneChunkFileOptimization)
                {
                    // We do check point consistancy validation in reader, and directly use it in writer.
                    if ((null != this.TransferJob.CheckPoint.TransferWindow) &&
                        this.TransferJob.CheckPoint.TransferWindow.Any())
                    {
                        this.TransferJob.CheckPoint.TransferWindow.Sort();
                        this.expectOffset = this.TransferJob.CheckPoint.TransferWindow[0];
                    }
                    else
                    {
                        this.expectOffset = this.TransferJob.CheckPoint.EntryTransferOffset;
                    }
                }

                if (TransferLocationType.Stream == this.TransferJob.Destination.Type)
                {
                    Stream streamInDestination = (this.TransferJob.Destination as StreamLocation).Stream;
                    if (!streamInDestination.CanWrite)
                    {
                        throw new NotSupportedException(string.Format(
                                                            CultureInfo.CurrentCulture,
                                                            Resources.StreamMustSupportWriteException,
                                                            "outputStream"));
                    }

                    if (!streamInDestination.CanSeek)
                    {
                        throw new NotSupportedException(string.Format(
                                                            CultureInfo.CurrentCulture,
                                                            Resources.StreamMustSupportSeekException,
                                                            "outputStream"));
                    }

                    this.outputStream = streamInDestination;
                }
                else
                {
                    string filePath = (this.TransferJob.Destination as FileLocation).FilePath;

                    if (!this.Controller.IsForceOverwrite)
                    {
                        await this.Controller.CheckOverwriteAsync(
                            LongPathFile.Exists(filePath),
                            this.TransferJob.Source.Instance,
                            filePath).ConfigureAwait(false);
                    }

                    this.Controller.CheckCancellation();

                    try
                    {
                        FileMode fileMode = 0 == this.expectOffset ? FileMode.OpenOrCreate : FileMode.Open;

#if DOTNET5_4
                        string longFilePath = filePath;
                        if (Interop.CrossPlatformHelpers.IsWindows)
                        {
                            longFilePath = LongPath.ToUncPath(longFilePath);
                        }

                        // Attempt to open the file first so that we throw an exception before getting into the async work
                        this.outputStream = new FileStream(
                            longFilePath,
                            fileMode,
                            FileAccess.ReadWrite,
                            FileShare.None);
#else
                        this.outputStream = LongPathFile.Open(
                            filePath,
                            fileMode,
                            FileAccess.ReadWrite,
                            FileShare.None);
#endif

                        this.ownsStream = true;
                    }
                    catch (Exception ex)
                    {
                        string exceptionMessage = string.Format(
                            CultureInfo.CurrentCulture,
                            Resources.FailedToOpenFileException,
                            filePath,
                            ex.Message);

                        throw new TransferException(
                            TransferErrorCode.OpenFileFailed,
                            exceptionMessage,
                            ex);
                    }
                }

                this.outputStream.SetLength(this.SharedTransferData.TotalLength);

                this.md5HashStream = new MD5HashStream(
                    this.outputStream,
                    this.expectOffset,
                    !this.SharedTransferData.DisableContentMD5Validation);

                if (this.md5HashStream.FinishedSeparateMd5Calculator)
                {
                    this.state = State.Write;
                }
                else
                {
                    this.state = State.CalculateMD5;
                }

                this.PreProcessed = true;

                // Switch state internal for one chunk small file.
                if (this.EnableOneChunkFileOptimization &&
                    State.Write == this.state &&
                    ((this.SharedTransferData.TotalLength == this.expectOffset) || this.SharedTransferData.AvailableData.ContainsKey(this.expectOffset)))
                {
                    this.isStateSwitchedInternal = true;
                    await this.WriteChunkDataAsync().ConfigureAwait(false);
                }
                else
                {
                    this.workToken = 1;
                }
            });
        }
Пример #6
0
        public IsolatedStorageFileStream(String path, FileMode mode,
                                         FileAccess access, FileShare share, int bufferSize,
                                         IsolatedStorageFile isf)
        {
            if (path == null)
            {
                throw new ArgumentNullException("path");
            }
            Contract.EndContractBlock();

#if FEATURE_PAL
            if (s_BackSlash == null)
            {
                s_BackSlash = new String(System.IO.Path.DirectorySeparatorChar, 1);
            }
#endif // FEATURE_PAL

            if ((path.Length == 0) || path.Equals(s_BackSlash))
            {
                throw new ArgumentException(
                          Environment.GetResourceString(
                              "IsolatedStorage_Path"));
            }

            if (isf == null)
            {
#if FEATURE_ISOSTORE_LIGHT
                throw new ArgumentNullException("isf");
#else // !FEATURE_ISOSTORE_LIGHT
                m_OwnedStore = true;
                isf          = IsolatedStorageFile.GetUserStoreForDomain();
#endif // !FEATURE_ISOSTORE_LIGHT
            }

            if (isf.Disposed)
            {
                throw new ObjectDisposedException(null, Environment.GetResourceString("IsolatedStorage_StoreNotOpen"));
            }

            switch (mode)
            {
            case FileMode.CreateNew:            // Assume new file
            case FileMode.Create:               // Check for New file & Unreserve
            case FileMode.OpenOrCreate:         // Check for new file
            case FileMode.Truncate:             // Unreserve old file size
            case FileMode.Append:               // Check for new file
            case FileMode.Open:                 // Open existing, else exception
                break;

            default:
                throw new ArgumentException(Environment.GetResourceString("IsolatedStorage_FileOpenMode"));
            }

            m_isf = isf;

#if !FEATURE_CORECLR
            FileIOPermission fiop =
                new FileIOPermission(FileIOPermissionAccess.AllAccess,
                                     m_isf.RootDirectory);

            fiop.Assert();
            fiop.PermitOnly();
#endif

            m_GivenPath = path;
            m_FullPath  = m_isf.GetFullPath(m_GivenPath);

#if FEATURE_ISOLATED_STORAGE_QUOTA_ENFORCEMENT
            ulong oldFileSize = 0, newFileSize;
            bool  fNewFile = false, fLock = false;

            RuntimeHelpers.PrepareConstrainedRegions();
            try { // for finally Unlocking locked store
                  // Cache the old file size if the file size could change
                  // Also find if we are going to create a new file.

                switch (mode)
                {
                case FileMode.CreateNew:            // Assume new file
#if FEATURE_ISOSTORE_LIGHT
                    // We are going to call Reserve so we need to lock the store.
                    m_isf.Lock(ref fLock);
#endif
                    fNewFile = true;
                    break;

                case FileMode.Create:               // Check for New file & Unreserve
                case FileMode.OpenOrCreate:         // Check for new file
                case FileMode.Truncate:             // Unreserve old file size
                case FileMode.Append:               // Check for new file

                    m_isf.Lock(ref fLock);          // oldFileSize needs to be
                    // protected

                    try {
#if FEATURE_ISOSTORE_LIGHT
                        oldFileSize = IsolatedStorageFile.RoundToBlockSize((ulong)(FileInfo.UnsafeCreateFileInfo(m_FullPath).Length));
#else
                        oldFileSize = IsolatedStorageFile.RoundToBlockSize((ulong)LongPathFile.GetLength(m_FullPath));
#endif
                    } catch (FileNotFoundException) {
                        fNewFile = true;
                    } catch {
                    }

                    break;

                case FileMode.Open:                 // Open existing, else exception
                    break;
                }

                if (fNewFile)
                {
                    m_isf.ReserveOneBlock();
                }
#endif // FEATURE_ISOLATED_STORAGE_QUOTA_ENFORCEMENT

            try {
#if FEATURE_CORECLR
                // Since FileStream's .ctor won't do a demand, we need to do our access check here.
                m_isf.Demand(m_FullPath);
#endif

#if FEATURE_ISOSTORE_LIGHT
                m_fs = new
                       FileStream(m_FullPath, mode, access, share, bufferSize,
                                  FileOptions.None, m_GivenPath, true);
            } catch (Exception e) {
#else
                m_fs = new
                       FileStream(m_FullPath, mode, access, share, bufferSize,
                                  FileOptions.None, m_GivenPath, true, true);
            } catch {
#endif
#if FEATURE_ISOLATED_STORAGE_QUOTA_ENFORCEMENT
                if (fNewFile)
                {
                    m_isf.UnreserveOneBlock();
                }
#endif // FEATURE_ISOLATED_STORAGE_QUOTA_ENFORCEMENT
#if FEATURE_ISOSTORE_LIGHT
                // IsoStore generally does not let arbitrary exceptions flow out: a
                // IsolatedStorageException is thrown instead (see examples in IsolatedStorageFile.cs
                // Keeping this scoped to coreclr just because changing the exception type thrown is a
                // breaking change and that should not be introduced into the desktop without deliberation.
                //
                // Note that GetIsolatedStorageException may set InnerException. To the real exception
                // Today it always does this, for debug and chk builds, and for other builds asks the host
                // if it is okay to do so.
                throw IsolatedStorageFile.GetIsolatedStorageException("IsolatedStorage_Operation_ISFS", e);
#else
                throw;
#endif // FEATURE_ISOSTORE_LIGHT
            }

#if FEATURE_ISOLATED_STORAGE_QUOTA_ENFORCEMENT
            // make adjustment to the Reserve / Unreserve state

            if ((fNewFile == false) &&
                ((mode == FileMode.Truncate) || (mode == FileMode.Create)))
            {
                newFileSize = IsolatedStorageFile.RoundToBlockSize((ulong)m_fs.Length);

                if (oldFileSize > newFileSize)
                {
                    m_isf.Unreserve(oldFileSize - newFileSize);
                }
                else if (newFileSize > oldFileSize)         // Can this happen ?
                {
                    m_isf.Reserve(newFileSize - oldFileSize);
                }
            }
        }

        finally {
            if (fLock)
            {
                m_isf.Unlock();
            }
        }
#endif // FEATURE_ISOLATED_STORAGE_QUOTA_ENFORCEMENT

#if !FEATURE_CORECLR
            CodeAccessPermission.RevertAll();
#endif
        }
Пример #7
0
        private static IEnumerable <LocalEnumerateItem> InternalEnumerateInDirectory(
            string directoryName,
            string filePattern,
            string fromFilePath,
            SearchOption searchOption,
            bool followsymlink,
            bool returnDirectories,
            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 ex)
                        {
                            if (!TransferManager.Configurations.SupportUncPath)
                            {
                                throw new TransferException(string.Format(CultureInfo.CurrentCulture, Resources.FailedToGetFileInfoException, filePath), ex);
                            }
                        }
                        catch (IOException ex)
                        {
                            if (!TransferManager.Configurations.SupportUncPath)
                            {
                                throw new TransferException(string.Format(CultureInfo.CurrentCulture, Resources.FailedToGetFileInfoException, filePath), ex);
                            }
                        }
                        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(new LocalEnumerateItem()
                                {
                                    Path = LongPath.Combine(folder, fileEntryInfo.FileName),
                                    IsDirectory = false
                                });
                            }
                            else
                            {
                                if (CrossPlatformHelpers.IsLinux)
                                {
                                    if (!passedContinuationToken)
                                    {
                                        if (string.Equals(fileEntryInfo.FileName, continuationTokenFile, StringComparison.Ordinal))
                                        {
                                            passedContinuationToken = true;
                                        }
                                    }
                                    else
                                    {
                                        yield return(new LocalEnumerateItem()
                                        {
                                            Path = LongPath.Combine(folder, fileEntryInfo.FileName),
                                            IsDirectory = false
                                        });
                                    }
                                }
                                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(new LocalEnumerateItem()
                                        {
                                            Path = LongPath.Combine(folder, fileEntryInfo.FileName),
                                            IsDirectory = false
                                        });
                                    }
                                }
                            }
                        }
                    }

                    // 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)
                                {
                                    if (returnDirectories)
                                    {
                                        yield return(new LocalEnumerateItem()
                                        {
                                            Path = LongPath.Combine(folder, fileEntryInfo.FileName),
                                            IsDirectory = true
                                        });
                                    }
                                    else
                                    {
                                        currentFolderSubFolders.Push(LongPath.Combine(folder, fileEntryInfo.FileName));
                                    }
                                }
                                else
                                {
                                    if (CrossPlatformHelpers.IsLinux)
                                    {
                                        if (string.Equals(fileEntryInfo.FileName, fromSubfolder, StringComparison.Ordinal))
                                        {
                                            passedSubfoler = true;

                                            if (returnDirectories)
                                            {
                                                yield return(new LocalEnumerateItem()
                                                {
                                                    Path = LongPath.Combine(folder, fileEntryInfo.FileName),
                                                    IsDirectory = true
                                                });
                                            }
                                            else
                                            {
                                                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;

                                            if (returnDirectories)
                                            {
                                                yield return(new LocalEnumerateItem()
                                                {
                                                    Path = LongPath.Combine(folder, fileEntryInfo.FileName),
                                                    IsDirectory = true
                                                });
                                            }
                                            else
                                            {
                                                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());
                        }
                    }
                }
            }
        }
Пример #8
0
 public static FileStream Open(string path, FileMode mode)
 {
     return(LongPathFile.Open(path, mode, FileAccess.ReadWrite, FileShare.ReadWrite));
 }
Пример #9
0
 public static FileStream Open(string path, FileMode mode, FileAccess access, FileShare share)
 {
     return(LongPathFile.Open(path, mode, access, share));
 }
Пример #10
0
        private async Task HandleOutputStreamAsync()
        {
            this.hasWork = false;

            await Task.Run(() =>
            {
                // We do check point consistancy validation in reader, and directly use it in writer.
                if ((null != this.TransferJob.CheckPoint.TransferWindow) &&
                    (this.TransferJob.CheckPoint.TransferWindow.Any()))
                {
                    this.TransferJob.CheckPoint.TransferWindow.Sort();
                    this.expectOffset = this.TransferJob.CheckPoint.TransferWindow[0];
                }
                else
                {
                    this.expectOffset = this.TransferJob.CheckPoint.EntryTransferOffset;
                }

                if (TransferLocationType.Stream == this.TransferJob.Destination.Type)
                {
                    Stream streamInDestination = (this.TransferJob.Destination as StreamLocation).Stream;
                    if (!streamInDestination.CanWrite)
                    {
                        throw new NotSupportedException(string.Format(
                                                            CultureInfo.CurrentCulture,
                                                            Resources.StreamMustSupportWriteException,
                                                            "outputStream"));
                    }

                    if (!streamInDestination.CanSeek)
                    {
                        throw new NotSupportedException(string.Format(
                                                            CultureInfo.CurrentCulture,
                                                            Resources.StreamMustSupportSeekException,
                                                            "outputStream"));
                    }

                    this.outputStream = streamInDestination;
                }
                else
                {
                    string filePath = (this.TransferJob.Destination as FileLocation).FilePath;

                    if (!this.Controller.IsForceOverwrite)
                    {
                        this.Controller.CheckOverwrite(
                            LongPathFile.Exists(filePath),
                            this.TransferJob.Source.Instance,
                            filePath);
                    }

                    this.Controller.UpdateProgressAddBytesTransferred(0);

                    this.Controller.CheckCancellation();

                    try
                    {
                        FileMode fileMode = 0 == this.expectOffset ? FileMode.OpenOrCreate : FileMode.Open;

#if DOTNET5_4
                        string longFilePath = filePath;
                        if (Interop.CrossPlatformHelpers.IsWindows)
                        {
                            longFilePath = LongPath.ToUncPath(longFilePath);
                        }
                        // Attempt to open the file first so that we throw an exception before getting into the async work
                        this.outputStream = new FileStream(
                            longFilePath,
                            fileMode,
                            FileAccess.ReadWrite,
                            FileShare.None);
#else
                        this.outputStream = LongPathFile.Open(
                            filePath,
                            fileMode,
                            FileAccess.ReadWrite,
                            FileShare.None);
#endif

                        this.ownsStream = true;
                    }
                    catch (Exception ex)
                    {
                        string exceptionMessage = string.Format(
                            CultureInfo.CurrentCulture,
                            Resources.FailedToOpenFileException,
                            filePath,
                            ex.Message);

                        throw new TransferException(
                            TransferErrorCode.OpenFileFailed,
                            exceptionMessage,
                            ex);
                    }
                }

                this.outputStream.SetLength(this.SharedTransferData.TotalLength);

                this.Controller.UpdateProgressAddBytesTransferred(0);

                this.md5HashStream = new MD5HashStream(
                    this.outputStream,
                    this.expectOffset,
                    !this.SharedTransferData.DisableContentMD5Validation);

                if (this.md5HashStream.FinishedSeparateMd5Calculator)
                {
                    this.state = State.Write;
                }
                else
                {
                    this.state = State.CalculateMD5;
                }

                this.PreProcessed = true;
                this.hasWork      = true;
            });
        }
Пример #11
0
        public IsolatedStorageFileStream(string path, FileMode mode, FileAccess access, FileShare share, int bufferSize, IsolatedStorageFile isf)
        {
            if (path == null)
            {
                throw new ArgumentNullException("path");
            }
            if ((path.Length == 0) || path.Equals(@"\"))
            {
                throw new ArgumentException(Environment.GetResourceString("IsolatedStorage_Path"));
            }
            ulong num    = 0L;
            bool  flag   = false;
            bool  locked = false;

            if (isf == null)
            {
                this.m_OwnedStore = true;
                isf = IsolatedStorageFile.GetUserStoreForDomain();
            }
            if (isf.Disposed)
            {
                throw new ObjectDisposedException(null, Environment.GetResourceString("IsolatedStorage_StoreNotOpen"));
            }
            this.m_isf = isf;
            FileIOPermission permission = new FileIOPermission(FileIOPermissionAccess.AllAccess, this.m_isf.RootDirectory);

            permission.Assert();
            permission.PermitOnly();
            this.m_GivenPath = path;
            this.m_FullPath  = this.m_isf.GetFullPath(this.m_GivenPath);
            RuntimeHelpers.PrepareConstrainedRegions();
            try
            {
                switch (mode)
                {
                case FileMode.CreateNew:
                    flag = true;
                    break;

                case FileMode.Create:
                case FileMode.OpenOrCreate:
                case FileMode.Truncate:
                case FileMode.Append:
                    this.m_isf.Lock(ref locked);
                    try
                    {
                        num = IsolatedStorageFile.RoundToBlockSize((ulong)LongPathFile.GetLength(this.m_FullPath));
                    }
                    catch (FileNotFoundException)
                    {
                        flag = true;
                    }
                    catch
                    {
                    }
                    break;

                case FileMode.Open:
                    break;

                default:
                    throw new ArgumentException(Environment.GetResourceString("IsolatedStorage_FileOpenMode"));
                }
                if (flag)
                {
                    this.m_isf.ReserveOneBlock();
                }
                try
                {
                    this.m_fs = new FileStream(this.m_FullPath, mode, access, share, bufferSize, FileOptions.None, this.m_GivenPath, true, true);
                }
                catch
                {
                    if (flag)
                    {
                        this.m_isf.UnreserveOneBlock();
                    }
                    throw;
                }
                if (!flag && ((mode == FileMode.Truncate) || (mode == FileMode.Create)))
                {
                    ulong num2 = IsolatedStorageFile.RoundToBlockSize((ulong)this.m_fs.Length);
                    if (num > num2)
                    {
                        this.m_isf.Unreserve(num - num2);
                    }
                    else if (num2 > num)
                    {
                        this.m_isf.Reserve(num2 - num);
                    }
                }
            }
            finally
            {
                if (locked)
                {
                    this.m_isf.Unlock();
                }
            }
            CodeAccessPermission.RevertAll();
        }
 public static void SetAttributes(string path, FileAttributes fileAttributes)
 {
     path = LongPath.ToUncPath(path);
     LongPathFile.SetAttributes(path, fileAttributes);
 }