public void ClearContent(string path)
        {
            StreamContentReaderWriter stream      = null;
            ZipFileItemInfo           archiveFile = GetItemHelper(path);

            archiveFile.ClearContent();
        }
Exemplo n.º 2
0
        /// <summary>
        /// Removes the specified file or directory.
        /// </summary>
        /// <param name="path">
        /// The full path to the file or directory to be removed.
        /// </param>
        /// <param name="recurse">
        /// Specifies if the operation should also remove child items.
        /// </param>
        /// <exception cref="System.ArgumentException">
        ///     path is null or empty.
        /// </exception>
        protected override void RemoveItem(string path, bool recurse)
        {
            if (string.IsNullOrEmpty(path))
            {
                throw PSTraceSource.NewArgumentException("path");
            }

            path = NormalizePath(path);
            if (!ItemExists(path))
            {
                throw new Exception("Item not exists");
            }
            ZipFileItemInfo ArchiveItem = GetItemHelper(path);
            ArchiveItem.Delete();
        }
        /// <summary>
        /// Gets the item at the specified path.
        /// </summary>
        /// <param name="path">
        /// A fully qualified path representing a file or directory in the
        /// file system.
        /// </param>
        /// <returns>
        /// Nothing.  FileInfo and DirectoryInfo objects are written to the
        /// context's pipeline.
        /// </returns>
        /// <exception cref="System.ArgumentException">
        ///     path is null or empty.
        /// </exception>
        protected override void GetItem(string path)
        {
            path = NormalizePath(path);


            // Validate the argument
            bool isContainer = false;

            if (string.IsNullOrEmpty(path))
            {
                // The parameter was null, throw an exception
                throw PSTraceSource.NewArgumentException("path");
            }

            try
            {
                ZipFileItemInfo result = new ZipFileItemInfo(PSDriveInfo, path);

                // FileSystemInfo result = GetFileSystemItem(path, ref isContainer, false);
                if (result != null)
                {
                    // Otherwise, return the item itself.
                    WriteItemObject(result, result.FullName, isContainer);
                }
                else
                {
                    string    error = StringUtil.Format(FileSystemProviderStrings.ItemNotFound, path);
                    Exception e     = new IOException(error);
                    WriteError(new ErrorRecord(
                                   e,
                                   "ItemNotFound",
                                   ErrorCategory.ObjectNotFound,
                                   path));
                }
            }
            catch (IOException ioError)
            {
                // IOException contains specific message about the error occured and so no need for errordetails.
                ErrorRecord er = new ErrorRecord(ioError, "GetItemIOError", ErrorCategory.ReadError, path);
                WriteError(er);
            }
            catch (UnauthorizedAccessException accessException)
            {
                WriteError(new ErrorRecord(accessException, "GetItemUnauthorizedAccessError", ErrorCategory.PermissionDenied, path));
            }
        }
Exemplo n.º 4
0
        /// <summary>
        /// Creates a file or directory with the given path.
        /// </summary>
        /// <param name="path">
        /// The path of the file or directory to create.
        /// </param>
        ///<param name="type">
        /// Specify "file" to create a file.
        /// Specify "directory" or "container" to create a directory.
        /// </param>
        /// <param name="value">
        /// If <paramref name="type" /> is "file" then this parameter becomes the content
        /// of the file to be created.
        /// </param>
        /// <returns>
        /// Nothing.  The new DirectoryInfo or FileInfo object is
        /// written to the context's pipeline.
        /// </returns>
        /// <exception cref="System.ArgumentException">
        ///     path is null or empty.
        ///     type is null or empty.
        /// </exception>
        protected override void NewItem(
            string path,
            string type,
            object value)
        {
            //ItemType itemType = ItemType.Unknown;

            // Verify parameters
            if (string.IsNullOrEmpty(path))
            {
                throw PSTraceSource.NewArgumentException("path");
            }

            if (string.IsNullOrEmpty(type))
            {
                type = "file";
            }

            path = NormalizePath(path);

            // if (Force)
            // {
            //     if (!CreateIntermediateDirectories(path))
            //     {
            //         return;
            //     }
            // }
            if (ItemExists(path))
            {
                throw new Exception("File Exists");
            }

            if (type == "file")
            {
                ZipFileItemInfo newItem = NewItemHelper(path);
                if (value != null)
                {
                    using (StreamWriter writer = newItem.AppendText())
                    {
                        writer.Write(value.ToString());
                        writer.Flush();
                        writer.Dispose();
                    }
                }
            }
        }
        internal ZipFileItemInfo NewItemHelper(string path)
        {
            try {
                using (ZipArchive zipArchive = ZipFile.Open(PSDriveInfo.Root, ZipArchiveMode.Update))
                {
                    path = NormalizePath(path);
                    ZipArchiveEntry zipArchiveEntry = zipArchive.CreateEntry(path);

                    ZipFileItemInfo zipFileItemInfo = new ZipFileItemInfo(zipArchiveEntry, PSDriveInfo);

                    return(zipFileItemInfo);
                }
            }
            catch (Exception e) {
                throw e;
            }
        }
        protected override void GetChildItems(string path, bool recurse)
        {
            path = NormalizePath(path);

            if (String.IsNullOrEmpty(path))
            {
                path = "*";
            }
            // WriteWarning($"[TODO] GetChildItems(string path) '{path}'");

            List <ZipFileItemInfo> results = ZipFileItemInfo.GetFileItemInfo(PSDriveInfo, path);

            foreach (ZipFileItemInfo entry in results)
            {
                WriteItemObject(entry, entry.FullName, false);
            }
        }
        /// <summary>
        /// Determines if the specified path is syntactically and semantically valid.
        /// An example path looks like this
        ///     C:\WINNT\Media\chimes.wav.
        /// </summary>
        /// <param name="path">
        /// The fully qualified path to validate.
        /// </param>
        /// <returns>
        /// True if the path is valid, false otherwise.
        /// </returns>
        protected override bool IsValidPath(string path)
        {
            // Path passed should be fully qualified path.
            if (string.IsNullOrEmpty(path))
            {
                return(false);
            }


            Console.WriteLine($"IsValidPath('{path}')");
            // Normalize the path
            path = NormalizePath(path);
            // path = EnsureDriveIsRooted(path);

            // Make sure the path is either drive rooted or UNC Path
            if (!IsAbsolutePath(path) && !Utils.PathIsUnc(path))
            {
                return(false);
            }

            // Exceptions should only deal with exceptional circumstances,
            // but unfortunately, FileInfo offers no Try() methods that
            // let us check if we _could_ open the file.
            try
            {
                ZipFileItemInfo testFile = new ZipFileItemInfo(PSDriveInfo, path);
            }
            catch (Exception e)
            {
                if ((e is ArgumentNullException) ||
                    (e is ArgumentException) ||
                    (e is System.Security.SecurityException) ||
                    (e is UnauthorizedAccessException) ||
                    (e is PathTooLongException) ||
                    (e is NotSupportedException))
                {
                    return(false);
                }
                else
                {
                    throw;
                }
            }
            return(false);
        }
Exemplo n.º 8
0
        /// <summary>
        /// Renames a file or directory.
        /// </summary>
        ///
        /// <param name="path">
        /// The current full path to the file or directory.
        /// </param>
        ///
        /// <param name="newName">
        /// The new full path to the file or directory.
        /// </param>
        ///
        /// <returns>
        /// Nothing.  The renamed DirectoryInfo or FileInfo object is
        /// written to the context's pipeline.
        /// </returns>
        ///
        /// <exception cref="System.ArgumentException">
        ///     path is null or empty.
        ///     newName is null or empty
        /// </exception>
        protected override void RenameItem(string path, string newName)
        {
            // Check the parameters
            if (String.IsNullOrEmpty(path))
            {
                throw PSTraceSource.NewArgumentException("path");
            }

            path = NormalizePath(path);

            if (String.IsNullOrEmpty(newName))
            {
                throw PSTraceSource.NewArgumentException("newName");
            }

            newName = NormalizePath(newName);

            // Clean up "newname" to fix some common usability problems:
            // Rename .\foo.txt .\bar.txt
            // Rename c:\temp\foo.txt c:\temp\bar.txt
            if (newName.StartsWith(".\\", StringComparison.OrdinalIgnoreCase) ||
                newName.StartsWith("./", StringComparison.OrdinalIgnoreCase))
            {
                newName = newName.Remove(0, 2);
            }
            //else if (String.Equals(Path.GetDirectoryName(path), Path.GetDirectoryName(newName), StringComparison.OrdinalIgnoreCase))
            //{
            //    newName = Path.GetFileName(newName);
            //}

            // Check to see if the target specified exists.
            if (ItemExists(newName))
            {
                throw PSTraceSource.NewArgumentException("newName", FileSystemProviderStrings.RenameError);
            }

            try
            {
                // Manually move this item since you cant have more than one stream open at a time.
                ZipFileItemInfo file = new ZipFileItemInfo(PSDriveInfo, path);
                ZipFileItemInfo result;

                // Confirm the rename with the user

                string action = FileSystemProviderStrings.RenameItemActionFile;

                string resource = StringUtil.Format(FileSystemProviderStrings.RenameItemResourceFileTemplate, file.FullName, newName);

                if (ShouldProcess(resource, action))
                {
                    // Now move the file
                    file.MoveTo(newName);

                    result = file;
                    WriteItemObject(result, result.FullName, false);
                }
            }
            catch (ArgumentException argException)
            {
                WriteError(new ErrorRecord(argException, "RenameItemArgumentError", ErrorCategory.InvalidArgument, path));
            }
            catch (IOException ioException)
            {
                //IOException contains specific message about the error occured and so no need for errordetails.
                WriteError(new ErrorRecord(ioException, "RenameItemIOError", ErrorCategory.WriteError, path));
            }
            catch (UnauthorizedAccessException accessException)
            {
                WriteError(new ErrorRecord(accessException, "RenameItemUnauthorizedAccessError", ErrorCategory.PermissionDenied, path));
            }
        }
Exemplo n.º 9
0
 public ZipFileContentStream(ZipFileItemInfo archiveFileInfo, FileMode mode, string delimiter, Encoding encoding, bool usingByteEncoding, CmdletProvider provider, bool isRawStream)
     : base(archiveFileInfo.Open(mode), delimiter, encoding, provider, isRawStream)
 {
     _provider = provider;
 }
Exemplo n.º 10
0
 public ZipFileContentStream(ZipFileItemInfo archiveFileInfo, FileMode mode, Encoding encoding, bool usingByteEncoding, CmdletProvider provider, bool isRawStream, bool suppressNewline)
     : base(archiveFileInfo.Open(mode), encoding, usingByteEncoding, provider, isRawStream, suppressNewline)
 {
     _provider = provider;
 }
        /// <summary>
        /// Creates an instance of the FileSystemContentStream class, opens
        /// the specified file for reading, and returns the IContentReader interface
        /// to it.
        /// </summary>
        /// <param name="path">
        /// The path of the file to be opened for reading.
        /// </param>
        /// <returns>
        /// An IContentReader for the specified file.
        /// </returns>
        /// <exception cref="System.ArgumentException">
        ///     path is null or empty.
        /// </exception>
        public IContentReader GetContentReader(string path)
        {
            if (string.IsNullOrEmpty(path))
            {
                throw PSTraceSource.NewArgumentException("path");
            }

            path = NormalizePath(path);

            // Defaults for the file read operation
            string delimiter = "\n";

            // Encoding encoding = Encoding.Default;
            Encoding encoding = ClrFacade.GetDefaultEncoding();

            bool streamTypeSpecified = false;
            bool usingByteEncoding   = false;
            bool delimiterSpecified  = false;
            bool isRawStream         = false;

            // Get the dynamic parameters.
            // They override the defaults specified above.
            if (DynamicParameters != null)
            {
                StreamContentReaderDynamicParameters dynParams = DynamicParameters as StreamContentReaderDynamicParameters;
                if (dynParams != null)
                {
                    // -raw is not allowed when -first,-last or -wait is specified
                    // this call will validate that and throws.
                    ValidateParameters(dynParams.Raw);

                    isRawStream = dynParams.Raw;

                    // Get the delimiter
                    delimiterSpecified = dynParams.DelimiterSpecified;
                    if (delimiterSpecified)
                    {
                        delimiter = dynParams.Delimiter;
                    }

                    // Get the stream type
                    usingByteEncoding   = dynParams.AsByteStream;
                    streamTypeSpecified = dynParams.WasStreamTypeSpecified;

                    if (usingByteEncoding && streamTypeSpecified)
                    {
                        WriteWarning(FileSystemProviderStrings.EncodingNotUsed);
                    }

                    if (streamTypeSpecified)
                    {
                        encoding = dynParams.Encoding;
                    }
                }
            }
            StreamContentReaderWriter stream = null;

            ZipFileItemInfo archiveFile = GetItemHelper(path);

            //Archive.FileStream archiveStream = archiveFile.Open(FileMode.Append);

            try
            {
                // Users can't both read as bytes, and specify a delimiter
                if (delimiterSpecified)
                {
                    if (usingByteEncoding)
                    {
                        Exception e =
                            new ArgumentException(FileSystemProviderStrings.DelimiterError, "delimiter");
                        WriteError(new ErrorRecord(
                                       e,
                                       "GetContentReaderArgumentError",
                                       ErrorCategory.InvalidArgument,
                                       path));
                    }
                    else
                    {
                        //Console.WriteLine("Get-Content : Delimiter");
                        stream = new ZipFileContentStream(archiveFile, FileMode.Append, delimiter, encoding, usingByteEncoding, this, isRawStream);
                    }
                }
                else
                {
                    //Console.WriteLine("Get-Content : Default");
                    stream = new ZipFileContentStream(archiveFile, FileMode.Append, encoding, usingByteEncoding, this, isRawStream);
                }
            }
            catch (PathTooLongException pathTooLong)
            {
                WriteError(new ErrorRecord(pathTooLong, "GetContentReaderPathTooLongError", ErrorCategory.InvalidArgument, path));
            }
            catch (FileNotFoundException fileNotFound)
            {
                WriteError(new ErrorRecord(fileNotFound, "GetContentReaderFileNotFoundError", ErrorCategory.ObjectNotFound, path));
            }
            catch (DirectoryNotFoundException directoryNotFound)
            {
                WriteError(new ErrorRecord(directoryNotFound, "GetContentReaderDirectoryNotFoundError", ErrorCategory.ObjectNotFound, path));
            }
            catch (ArgumentException argException)
            {
                WriteError(new ErrorRecord(argException, "GetContentReaderArgumentError", ErrorCategory.InvalidArgument, path));
            }
            catch (IOException ioException)
            {
                // IOException contains specific message about the error occured and so no need for errordetails.
                WriteError(new ErrorRecord(ioException, "GetContentReaderIOError", ErrorCategory.ReadError, path));
            }
            catch (System.Security.SecurityException securityException)
            {
                WriteError(new ErrorRecord(securityException, "GetContentReaderSecurityError", ErrorCategory.PermissionDenied, path));
            }
            catch (UnauthorizedAccessException unauthorizedAccess)
            {
                WriteError(new ErrorRecord(unauthorizedAccess, "GetContentReaderUnauthorizedAccessError", ErrorCategory.PermissionDenied, path));
            }
            catch (Exception e)
            {
                WriteError(
                    new ErrorRecord(e, "Unhandled Error", ErrorCategory.InvalidArgument, path)
                    );
            }

            if (stream == null)
            {
                throw new Exception("Invalid stream");
            }

            return(stream);
        }