Example #1
0
        public void CopyFile(string sourceFileName, string destinationFileName, bool overwrite)
        {
            ArgumentException.ThrowIfNullOrEmpty(sourceFileName);
            ArgumentException.ThrowIfNullOrEmpty(destinationFileName);

            EnsureStoreIsValid();

            string sourceFileNameFullPath      = GetFullPath(sourceFileName);
            string destinationFileNameFullPath = GetFullPath(destinationFileName);

            try
            {
                File.Copy(sourceFileNameFullPath, destinationFileNameFullPath, overwrite);
            }
            catch (FileNotFoundException)
            {
                throw new FileNotFoundException(SR.Format(SR.PathNotFound_Path, sourceFileName));
            }
            catch (PathTooLongException)
            {
                throw;
            }
            catch (Exception e)
            {
                throw GetIsolatedStorageException(SR.IsolatedStorage_Operation, e);
            }
        }
Example #2
0
#pragma warning disable CS8765 // Nullability of parameter 'name' doesn't match overridden member
        public override string[]? GetValues(string name)
#pragma warning restore CS8765
        {
            ArgumentException.ThrowIfNullOrEmpty(name);

            return(base.GetValues(name));
        }
Example #3
0
        public void CopyFile(string sourceFileName, string destinationFileName)
        {
            ArgumentException.ThrowIfNullOrEmpty(sourceFileName);
            ArgumentException.ThrowIfNullOrEmpty(destinationFileName);

            CopyFile(sourceFileName, destinationFileName, false);
        }
Example #4
0
#pragma warning disable CS8765 // Nullability of parameter 'name' doesn't match overridden member
        public override void Remove(string name)
#pragma warning restore CS8765
        {
            ArgumentException.ThrowIfNullOrEmpty(name);

            base.Remove(name);
        }
Example #5
0
        // /// <summary>
        // /// Asynchronously extracts the contents of a stream that represents a tar archive into the specified directory.
        // /// </summary>
        // /// <param name="source">The stream containing the tar archive.</param>
        // /// <param name="destinationDirectoryName">The path of the destination directory where the filesystem entries should be extracted.</param>
        // /// <param name="overwriteFiles"><see langword="true"/> to overwrite files and directories in <paramref name="destinationDirectoryName"/>; <see langword="false"/> to avoid overwriting, and throw if any files or directories are found with existing names.</param>
        // /// <param name="cancellationToken">The token to monitor for cancellation requests. The default value is <see cref="CancellationToken.None" />.</param>
        // /// <returns>A task that represents the asynchronous extraction operation.</returns>
        // /// <remarks><para>Files of type <see cref="TarEntryType.BlockDevice"/>, <see cref="TarEntryType.CharacterDevice"/> or <see cref="TarEntryType.Fifo"/> can only be extracted in Unix platforms.</para>
        // /// <para>Elevation is required to extract a <see cref="TarEntryType.BlockDevice"/> or <see cref="TarEntryType.CharacterDevice"/> to disk.</para></remarks>
        // /// <exception cref="UnauthorizedAccessException">Operation not permitted due to insufficient permissions.</exception>
        // public static Task ExtractToDirectoryAsync(Stream source, string destinationDirectoryName, bool overwriteFiles, CancellationToken cancellationToken = default)
        // {
        //     throw new NotImplementedException();
        // }

        /// <summary>
        /// Extracts the contents of a tar file into the specified directory.
        /// </summary>
        /// <param name="sourceFileName">The path of the tar file to extract.</param>
        /// <param name="destinationDirectoryName">The path of the destination directory where the filesystem entries should be extracted.</param>
        /// <param name="overwriteFiles"><see langword="true"/> to overwrite files and directories in <paramref name="destinationDirectoryName"/>; <see langword="false"/> to avoid overwriting, and throw if any files or directories are found with existing names.</param>
        /// <remarks><para>Files of type <see cref="TarEntryType.BlockDevice"/>, <see cref="TarEntryType.CharacterDevice"/> or <see cref="TarEntryType.Fifo"/> can only be extracted in Unix platforms.</para>
        /// <para>Elevation is required to extract a <see cref="TarEntryType.BlockDevice"/> or <see cref="TarEntryType.CharacterDevice"/> to disk.</para></remarks>
        /// <exception cref="UnauthorizedAccessException">Operation not permitted due to insufficient permissions.</exception>
        public static void ExtractToDirectory(string sourceFileName, string destinationDirectoryName, bool overwriteFiles)
        {
            ArgumentException.ThrowIfNullOrEmpty(sourceFileName);
            ArgumentException.ThrowIfNullOrEmpty(destinationDirectoryName);

            // Rely on Path.GetFullPath for validation of paths
            sourceFileName           = Path.GetFullPath(sourceFileName);
            destinationDirectoryName = Path.GetFullPath(destinationDirectoryName);

            if (!File.Exists(sourceFileName))
            {
                throw new FileNotFoundException(string.Format(SR.IO_FileNotFound, sourceFileName));
            }

            if (!Directory.Exists(destinationDirectoryName))
            {
                throw new DirectoryNotFoundException(string.Format(SR.IO_PathNotFound_Path, destinationDirectoryName));
            }

            FileStreamOptions fileStreamOptions = new()
            {
                Access     = FileAccess.Read,
                BufferSize = 0x1000,
                Mode       = FileMode.Open,
                Share      = FileShare.Read
            };

            using FileStream archive = File.Open(sourceFileName, fileStreamOptions);

            ExtractToDirectoryInternal(archive, destinationDirectoryName, overwriteFiles, leaveOpen: false);
        }
Example #6
0
        public void Add(string host, int port, string authenticationType, NetworkCredential credential)
        {
            ArgumentException.ThrowIfNullOrEmpty(host);
            ArgumentNullException.ThrowIfNull(authenticationType);

            if (port < 0)
            {
                throw new ArgumentOutOfRangeException(nameof(port));
            }

            if ((credential is SystemNetworkCredential) &&
                !((string.Equals(authenticationType, NegotiationInfoClass.NTLM, StringComparison.OrdinalIgnoreCase)) ||
                  (string.Equals(authenticationType, NegotiationInfoClass.Kerberos, StringComparison.OrdinalIgnoreCase)) ||
                  (string.Equals(authenticationType, NegotiationInfoClass.Negotiate, StringComparison.OrdinalIgnoreCase)))
                )
            {
                throw new ArgumentException(SR.Format(SR.net_nodefaultcreds, authenticationType), nameof(authenticationType));
            }

            ++_version;

            var key = new CredentialHostKey(host, port, authenticationType);

            if (NetEventSource.Log.IsEnabled())
            {
                NetEventSource.Info(this, $"Adding key:[{key}], cred:[{credential.Domain}],[{credential.UserName}]");
            }

            _cacheForHosts ??= new Dictionary <CredentialHostKey, NetworkCredential>();
            _cacheForHosts.Add(key, credential);
        }
Example #7
0
        public void MoveDirectory(string sourceDirectoryName, string destinationDirectoryName)
        {
            ArgumentException.ThrowIfNullOrEmpty(sourceDirectoryName);
            ArgumentException.ThrowIfNullOrEmpty(destinationDirectoryName);

            EnsureStoreIsValid();

            string sourceDirectoryNameFullPath      = GetFullPath(sourceDirectoryName);
            string destinationDirectoryNameFullPath = GetFullPath(destinationDirectoryName);

            try
            {
                Directory.Move(sourceDirectoryNameFullPath, destinationDirectoryNameFullPath);
            }
            catch (DirectoryNotFoundException)
            {
                throw new DirectoryNotFoundException(SR.Format(SR.PathNotFound_Path, sourceDirectoryName));
            }
            catch (PathTooLongException)
            {
                throw;
            }
            catch (Exception e)
            {
                throw GetIsolatedStorageException(SR.IsolatedStorage_Operation, e);
            }
        }
Example #8
0
        // Moves a given file to a new location and potentially a new file name.
        // Optionally overwrites existing file.
        // This method does work across volumes.
        public void MoveTo(string destFileName, bool overwrite)
        {
            ArgumentException.ThrowIfNullOrEmpty(destFileName);

            string fullDestFileName = Path.GetFullPath(destFileName);

            // These checks are in place to ensure Unix error throwing happens the same way
            // as it does on Windows.These checks can be removed if a solution to
            // https://github.com/dotnet/runtime/issues/14885 is found that doesn't require
            // validity checks before making an API call.
            if (!new DirectoryInfo(Path.GetDirectoryName(FullName) !).Exists)
            {
                throw new DirectoryNotFoundException(SR.Format(SR.IO_PathNotFound_Path, FullName));
            }

            if (!Exists)
            {
                throw new FileNotFoundException(SR.Format(SR.IO_FileNotFound_FileName, FullName), FullName);
            }

            FileSystem.MoveFile(FullPath, fullDestFileName, overwrite);

            FullPath     = fullDestFileName;
            OriginalPath = destFileName;
            _name        = Path.GetFileName(fullDestFileName);

            // Flush any cached information about the file.
            Invalidate();
        }
        public override byte[] DeriveKeyFromHmac(
            ECDiffieHellmanPublicKey otherPartyPublicKey,
            HashAlgorithmName hashAlgorithm,
            byte[]?hmacKey,
            byte[]?secretPrepend,
            byte[]?secretAppend)
        {
            ArgumentNullException.ThrowIfNull(otherPartyPublicKey);
            ArgumentException.ThrowIfNullOrEmpty(hashAlgorithm.Name, nameof(hashAlgorithm));

            using (SafeNCryptSecretHandle secretAgreement = DeriveSecretAgreementHandle(otherPartyPublicKey))
            {
                Interop.NCrypt.SecretAgreementFlags flags = hmacKey == null ?
                                                            Interop.NCrypt.SecretAgreementFlags.UseSecretAsHmacKey :
                                                            Interop.NCrypt.SecretAgreementFlags.None;

                return(Interop.NCrypt.DeriveKeyMaterialHmac(
                           secretAgreement,
                           hashAlgorithm.Name,
                           hmacKey,
                           secretPrepend,
                           secretAppend,
                           flags));
            }
        }
Example #10
0
        /// <summary>
        ///   Verifies that a digital signature is valid for the provided data.
        /// </summary>
        /// <param name="data">An array that contains the signed data.</param>
        /// <param name="offset">The starting index of the signed portion of <paramref name="data"/>.</param>
        /// <param name="count">The number of bytes in <paramref name="data"/> that were signed.</param>
        /// <param name="signature">The signature to verify.</param>
        /// <param name="hashAlgorithm">The hash algorithm used to hash the data for the verification process.</param>
        /// <param name="signatureFormat">The encoding format for <paramref name="signature"/>.</param>
        /// <returns>
        ///   <see langword="true"/> if the digital signature is valid for the provided data; otherwise, <see langword="false"/>.
        /// </returns>
        /// <exception cref="ArgumentNullException">
        ///   <paramref name="data"/> or <paramref name="signature"/> is <see langword="null"/>.
        /// </exception>
        /// <exception cref="ArgumentOutOfRangeException">
        ///   <paramref name="signatureFormat"/> is not a known format.
        ///
        ///   -or-
        ///
        ///   <paramref name="offset" /> is less than zero.
        ///
        ///   -or-
        ///
        ///   <paramref name="count" /> is less than zero.
        ///
        ///   -or-
        ///
        ///   <paramref name="offset" /> + <paramref name="count"/> - 1 results in an index that is
        ///   beyond the upper bound of <paramref name="data"/>.
        /// </exception>
        /// <exception cref="ArgumentException">
        ///   <paramref name="hashAlgorithm"/> has a <see langword="null"/> or empty <see cref="HashAlgorithmName.Name"/>.
        /// </exception>
        /// <exception cref="CryptographicException">
        ///   An error occurred in the hashing or verification operation.
        /// </exception>
        public bool VerifyData(
            byte[] data,
            int offset,
            int count,
            byte[] signature,
            HashAlgorithmName hashAlgorithm,
            DSASignatureFormat signatureFormat)
        {
            ArgumentNullException.ThrowIfNull(data);
            if (offset < 0 || offset > data.Length)
            {
                throw new ArgumentOutOfRangeException(nameof(offset));
            }
            if (count < 0 || count > data.Length - offset)
            {
                throw new ArgumentOutOfRangeException(nameof(count));
            }
            ArgumentNullException.ThrowIfNull(signature);
            ArgumentException.ThrowIfNullOrEmpty(hashAlgorithm.Name, nameof(hashAlgorithm));
            if (!signatureFormat.IsKnownValue())
            {
                throw DSASignatureFormatHelpers.CreateUnknownValueException(signatureFormat);
            }

            return(VerifyDataCore(
                       new ReadOnlySpan <byte>(data, offset, count),
                       signature,
                       hashAlgorithm,
                       signatureFormat));
        }
Example #11
0
        internal FieldBuilder(TypeBuilder typeBuilder, string fieldName, Type type,
                              Type[]?requiredCustomModifiers, Type[]?optionalCustomModifiers, FieldAttributes attributes)
        {
            ArgumentException.ThrowIfNullOrEmpty(fieldName);

            if (fieldName[0] == '\0')
            {
                throw new ArgumentException(SR.Argument_IllegalName, nameof(fieldName));
            }

            ArgumentNullException.ThrowIfNull(type);

            if (type == typeof(void))
            {
                throw new ArgumentException(SR.Argument_BadFieldType);
            }

            m_fieldName   = fieldName;
            m_typeBuilder = typeBuilder;
            m_fieldType   = type;
            m_Attributes  = attributes & ~FieldAttributes.ReservedMask;

            SignatureHelper sigHelp = SignatureHelper.GetFieldSigHelper(m_typeBuilder.Module);

            sigHelp.AddArgument(type, requiredCustomModifiers, optionalCustomModifiers);

            byte[] signature = sigHelp.InternalGetSignature(out int sigLength);

            ModuleBuilder module = m_typeBuilder.GetModuleBuilder();

            m_fieldTok = TypeBuilder.DefineField(new QCallModule(ref module),
                                                 typeBuilder.TypeToken, fieldName, signature, sigLength, m_Attributes);
        }
Example #12
0
        // Constructor called when creating a new 'TarEntry*' instance that can be passed to a TarWriter.
        internal TarEntry(TarEntryType entryType, string entryName, TarFormat format)
        {
            ArgumentException.ThrowIfNullOrEmpty(entryName);

            // Throws if format is unknown or out of range
            TarHelpers.VerifyEntryTypeIsSupported(entryType, format, forWriting: false);

            _readerOfOrigin = null;

            _header = default;

            _header._extendedAttributes = new Dictionary <string, string>();

            _header._name     = entryName;
            _header._linkName = string.Empty;
            _header._typeFlag = entryType;
            _header._mode     = (int)TarHelpers.DefaultMode;

            _header._gName = string.Empty;
            _header._uName = string.Empty;

            DateTimeOffset now = DateTimeOffset.Now;

            _header._mTime = now;
            _header._aTime = now;
            _header._cTime = now;
        }
        /// <summary>
        /// Adds a country or region attribute.
        /// </summary>
        /// <param name="twoLetterCode">The two letter code of the country or region.</param>
        /// <exception cref="ArgumentNullException">
        /// <paramref name="twoLetterCode" /> is <see langword="null" />.
        /// </exception>
        /// <exception cref="ArgumentException">
        /// <paramref name="twoLetterCode" /> is not exactly two characters, or contains
        /// characters that are not A through Z.
        /// </exception>
        /// <remarks>
        /// <para>This encodes an attribute with the OID 2.5.4.6 as a PrintableString.</para>
        /// <para>
        /// <paramref name="twoLetterCode" /> should be a two letter ISO 3166 alpha-2 code, and
        /// will be normalized to upper case characters.
        /// </para>
        /// </remarks>
        public void AddCountryOrRegion(string twoLetterCode)
        {
            // ITU T-REC X.520 Annex A:
            // id-at-countryName
            // WITH SYNTAX CountryName
            // CountryName ::= PrintableString(SIZE (2))
            // An attribute value for country name is a string chosen from ISO 3166-1 alpha-2 or ISO 3166-3 alpha-2.
            // We can't reasonably enforce the ISO 3166 list, but we can ensure it's a two letter ISO code
            // and consists of alpha characters.

            ArgumentException.ThrowIfNullOrEmpty(twoLetterCode);
            ReadOnlySpan <char> twoLetterCodeSpan = twoLetterCode;

            // This could be a surrogate pair, but since we are encoding as a PrintableString,
            // those will be prohibited, so "Length" should be fine for checking the length of
            // the string.
            // Input must be A-Z per ISO 3166.
            if (twoLetterCode.Length != 2 || !IsAlpha(twoLetterCode[0]) || !IsAlpha(twoLetterCode[1]))
            {
                throw new ArgumentException(SR.Argument_X500_InvalidCountryOrRegion, nameof(twoLetterCode));
            }

            Span <char> fixupTwoLetterCode = stackalloc char[2];
            int         written            = twoLetterCodeSpan.ToUpperInvariant(fixupTwoLetterCode);

            Debug.Assert(written == 2);

            EncodeComponent(
                Oids.CountryOrRegionName,
                fixupTwoLetterCode,
                UniversalTagNumber.PrintableString,
                nameof(twoLetterCode));
Example #14
0
        private static OpenExistingResult OpenExistingWorker(string name, out Semaphore?result)
        {
#if TARGET_WINDOWS
            ArgumentException.ThrowIfNullOrEmpty(name);

            // Pass false to OpenSemaphore to prevent inheritedHandles
            SafeWaitHandle myHandle = Interop.Kernel32.OpenSemaphore(AccessRights, false, name);

            if (myHandle.IsInvalid)
            {
                result = null;
                int errorCode = Marshal.GetLastPInvokeError();

                if (errorCode == Interop.Errors.ERROR_FILE_NOT_FOUND || errorCode == Interop.Errors.ERROR_INVALID_NAME)
                {
                    return(OpenExistingResult.NameNotFound);
                }
                if (errorCode == Interop.Errors.ERROR_PATH_NOT_FOUND)
                {
                    return(OpenExistingResult.PathNotFound);
                }
                if (errorCode == Interop.Errors.ERROR_INVALID_HANDLE)
                {
                    return(OpenExistingResult.NameInvalid);
                }
                // this is for passed through NativeMethods Errors
                throw Win32Marshal.GetExceptionForLastWin32Error();
            }

            result = new Semaphore(myHandle);
            return(OpenExistingResult.Success);
#else
            throw new PlatformNotSupportedException(SR.PlatformNotSupported_NamedSynchronizationPrimitives);
#endif
        }
Example #15
0
        private ModuleBuilder DefineDynamicModuleInternalNoLock(string name)
        {
            ArgumentException.ThrowIfNullOrEmpty(name);
            if (name[0] == '\0')
            {
                throw new ArgumentException(SR.Argument_InvalidName, nameof(name));
            }

            // Create the dynamic module- only one ModuleBuilder per AssemblyBuilder can be created.
            if (_isManifestModuleUsedAsDefinedModule)
            {
                throw new InvalidOperationException(SR.InvalidOperation_NoMultiModuleAssembly);
            }

            Debug.Assert(_assemblyData != null, "_assemblyData is null in DefineDynamicModuleInternal");

            // Init(...) has already been called on _manifestModuleBuilder in InitManifestModule()
            ModuleBuilder dynModule = _manifestModuleBuilder;

            _assemblyData._moduleBuilderList.Add(dynModule);

            if (dynModule == _manifestModuleBuilder)
            {
                // We are reusing manifest module as user-defined dynamic module
                _isManifestModuleUsedAsDefinedModule = true;
            }

            return(dynModule);
        }
Example #16
0
        /// <summary>
        /// Copies an existing file to a new file.
        /// If <paramref name="overwrite"/> is false, an exception will be
        /// raised if the destination exists. Otherwise it will be overwritten.
        /// </summary>
        public static void Copy(string sourceFileName, string destFileName, bool overwrite)
        {
            ArgumentException.ThrowIfNullOrEmpty(sourceFileName);
            ArgumentException.ThrowIfNullOrEmpty(destFileName);

            FileSystem.CopyFile(Path.GetFullPath(sourceFileName), Path.GetFullPath(destFileName), overwrite);
        }
Example #17
0
        public NetworkCredential?GetCredential(string host, int port, string authenticationType)
        {
            ArgumentException.ThrowIfNullOrEmpty(host);
            ArgumentNullException.ThrowIfNull(authenticationType);
            if (port < 0)
            {
                throw new ArgumentOutOfRangeException(nameof(port));
            }

            if (_cacheForHosts == null)
            {
                if (NetEventSource.Log.IsEnabled())
                {
                    NetEventSource.Info(this, "CredentialCache::GetCredential short-circuiting because the dictionary is null.");
                }
                return(null);
            }

            var key = new CredentialHostKey(host, port, authenticationType);

            NetworkCredential?match;

            _cacheForHosts.TryGetValue(key, out match);

            if (NetEventSource.Log.IsEnabled())
            {
                NetEventSource.Info(this, $"Returning {((match == null) ? "null" : "(" + match.UserName + ":" + match.Domain + ")")}");
            }

            return(match);
        }
Example #18
0
        /// <summary>
        /// Asynchronously extracts the contents of a tar file into the specified directory.
        /// </summary>
        /// <param name="sourceFileName">The path of the tar file to extract.</param>
        /// <param name="destinationDirectoryName">The path of the destination directory where the filesystem entries should be extracted.</param>
        /// <param name="overwriteFiles"><see langword="true"/> to overwrite files and directories in <paramref name="destinationDirectoryName"/>; <see langword="false"/> to avoid overwriting, and throw if any files or directories are found with existing names.</param>
        /// <param name="cancellationToken">The token to monitor for cancellation requests. The default value is <see cref="CancellationToken.None" />.</param>
        /// <returns>A task that represents the asynchronous extraction operation.</returns>
        /// <remarks><para>Files of type <see cref="TarEntryType.BlockDevice"/>, <see cref="TarEntryType.CharacterDevice"/> or <see cref="TarEntryType.Fifo"/> can only be extracted in Unix platforms.</para>
        /// <para>Elevation is required to extract a <see cref="TarEntryType.BlockDevice"/> or <see cref="TarEntryType.CharacterDevice"/> to disk.</para></remarks>
        /// <exception cref="UnauthorizedAccessException">Operation not permitted due to insufficient permissions.</exception>
        public static Task ExtractToDirectoryAsync(string sourceFileName, string destinationDirectoryName, bool overwriteFiles, CancellationToken cancellationToken = default)
        {
            if (cancellationToken.IsCancellationRequested)
            {
                return(Task.FromCanceled(cancellationToken));
            }
            ArgumentException.ThrowIfNullOrEmpty(sourceFileName);
            ArgumentException.ThrowIfNullOrEmpty(destinationDirectoryName);

            // Rely on Path.GetFullPath for validation of paths
            sourceFileName           = Path.GetFullPath(sourceFileName);
            destinationDirectoryName = Path.GetFullPath(destinationDirectoryName);

            if (!File.Exists(sourceFileName))
            {
                return(Task.FromException(new FileNotFoundException(string.Format(SR.IO_FileNotFound, sourceFileName))));
            }

            if (!Directory.Exists(destinationDirectoryName))
            {
                return(Task.FromException(new DirectoryNotFoundException(string.Format(SR.IO_PathNotFound_Path, destinationDirectoryName))));
            }

            return(ExtractToDirectoryInternalAsync(sourceFileName, destinationDirectoryName, overwriteFiles, cancellationToken));
        }
Example #19
0
        public NamedPipeClientStream(string serverName, string pipeName, PipeDirection direction,
                                     PipeOptions options, TokenImpersonationLevel impersonationLevel, HandleInheritability inheritability)
            : base(direction, 0)
        {
            ArgumentException.ThrowIfNullOrEmpty(pipeName);
            ArgumentNullException.ThrowIfNull(serverName);
            if (serverName.Length == 0)
            {
                throw new ArgumentException(SR.Argument_EmptyServerName);
            }
            if ((options & ~(PipeOptions.WriteThrough | PipeOptions.Asynchronous | PipeOptions.CurrentUserOnly)) != 0)
            {
                throw new ArgumentOutOfRangeException(nameof(options), SR.ArgumentOutOfRange_OptionsInvalid);
            }
            if (impersonationLevel < TokenImpersonationLevel.None || impersonationLevel > TokenImpersonationLevel.Delegation)
            {
                throw new ArgumentOutOfRangeException(nameof(impersonationLevel), SR.ArgumentOutOfRange_ImpersonationInvalid);
            }
            if (inheritability < HandleInheritability.None || inheritability > HandleInheritability.Inheritable)
            {
                throw new ArgumentOutOfRangeException(nameof(inheritability), SR.ArgumentOutOfRange_HandleInheritabilityNoneOrInheritable);
            }
            if ((options & PipeOptions.CurrentUserOnly) != 0)
            {
                IsCurrentUserOnly = true;
            }

            _normalizedPipePath = GetPipePath(serverName, pipeName);
            _direction          = direction;
            _inheritability     = inheritability;
            _impersonationLevel = impersonationLevel;
            _pipeOptions        = options;
        }
Example #20
0
        private static OpenExistingResult OpenExistingWorker(string name, out EventWaitHandle?result)
        {
#if TARGET_WINDOWS
            ArgumentException.ThrowIfNullOrEmpty(name);

            result = null;
            SafeWaitHandle myHandle = Interop.Kernel32.OpenEvent(AccessRights, false, name);

            if (myHandle.IsInvalid)
            {
                int errorCode = Marshal.GetLastPInvokeError();

                if (errorCode == Interop.Errors.ERROR_FILE_NOT_FOUND || errorCode == Interop.Errors.ERROR_INVALID_NAME)
                {
                    return(OpenExistingResult.NameNotFound);
                }
                if (errorCode == Interop.Errors.ERROR_PATH_NOT_FOUND)
                {
                    return(OpenExistingResult.PathNotFound);
                }
                if (errorCode == Interop.Errors.ERROR_INVALID_HANDLE)
                {
                    return(OpenExistingResult.NameInvalid);
                }

                throw Win32Marshal.GetExceptionForWin32Error(errorCode, name);
            }
            result = new EventWaitHandle(myHandle);
            return(OpenExistingResult.Success);
#else
            throw new PlatformNotSupportedException(SR.PlatformNotSupported_NamedSynchronizationPrimitives);
#endif
        }
Example #21
0
        /// <summary>
        /// Initializes a new instance of the <see cref="System.IO.FileStream" /> class with the specified path, creation mode, read/write and sharing permission, the access other FileStreams can have to the same file, the buffer size,  additional file options and the allocation size.
        /// </summary>
        /// <param name="path">A relative or absolute path for the file that the current <see cref="System.IO.FileStream" /> instance will encapsulate.</param>
        /// <param name="options">An object that describes optional <see cref="System.IO.FileStream" /> parameters to use.</param>
        /// <exception cref="T:System.ArgumentNullException"><paramref name="path" /> or <paramref name="options" /> is <see langword="null" />.</exception>
        /// <exception cref="T:System.ArgumentException"><paramref name="path" /> is an empty string (""), contains only white space, or contains one or more invalid characters.
        /// -or-
        /// <paramref name="path" /> refers to a non-file device, such as <c>CON:</c>, <c>COM1:</c>, <c>LPT1:</c>, etc. in an NTFS environment.</exception>
        /// <exception cref="T:System.NotSupportedException"><paramref name="path" /> refers to a non-file device, such as <c>CON:</c>, <c>COM1:</c>, <c>LPT1:</c>, etc. in a non-NTFS environment.</exception>
        /// <exception cref="T:System.IO.FileNotFoundException">The file cannot be found, such as when <see cref="System.IO.FileStreamOptions.Mode" /> is <see langword="FileMode.Truncate" /> or <see langword="FileMode.Open" />, and the file specified by <paramref name="path" /> does not exist. The file must already exist in these modes.</exception>
        /// <exception cref="T:System.IO.IOException">An I/O error, such as specifying <see langword="FileMode.CreateNew" /> when the file specified by <paramref name="path" /> already exists, occurred.
        ///  -or-
        ///  The stream has been closed.
        ///  -or-
        ///  The disk was full (when <see cref="System.IO.FileStreamOptions.PreallocationSize" /> was provided and <paramref name="path" /> was pointing to a regular file).
        ///  -or-
        ///  The file was too large (when <see cref="System.IO.FileStreamOptions.PreallocationSize" /> was provided and <paramref name="path" /> was pointing to a regular file).</exception>
        /// <exception cref="T:System.Security.SecurityException">The caller does not have the required permission.</exception>
        /// <exception cref="T:System.IO.DirectoryNotFoundException">The specified path is invalid, such as being on an unmapped drive.</exception>
        /// <exception cref="T:System.UnauthorizedAccessException">The <see cref="System.IO.FileStreamOptions.Access" /> requested is not permitted by the operating system for the specified <paramref name="path" />, such as when <see cref="System.IO.FileStreamOptions.Access" />  is <see cref="System.IO.FileAccess.Write" /> or <see cref="System.IO.FileAccess.ReadWrite" /> and the file or directory is set for read-only access.
        ///  -or-
        /// <see cref="F:System.IO.FileOptions.Encrypted" /> is specified for <see cref="System.IO.FileStreamOptions.Options" /> , but file encryption is not supported on the current platform.</exception>
        /// <exception cref="T:System.IO.PathTooLongException">The specified path, file name, or both exceed the system-defined maximum length. </exception>
        public FileStream(string path, FileStreamOptions options)
        {
            ArgumentException.ThrowIfNullOrEmpty(path);
            ArgumentNullException.ThrowIfNull(options);
            if ((options.Access & FileAccess.Read) != 0 && options.Mode == FileMode.Append)
            {
                throw new ArgumentException(SR.Argument_InvalidAppendMode, nameof(options));
            }
            else if ((options.Access & FileAccess.Write) == 0)
            {
                if (options.Mode == FileMode.Truncate || options.Mode == FileMode.CreateNew || options.Mode == FileMode.Create || options.Mode == FileMode.Append)
                {
                    throw new ArgumentException(SR.Format(SR.Argument_InvalidFileModeAndAccessCombo, options.Mode, options.Access), nameof(options));
                }
            }

            if (options.PreallocationSize > 0)
            {
                FileStreamHelpers.ValidateArgumentsForPreallocation(options.Mode, options.Access);
            }

            if (options.UnixCreateMode.HasValue)
            {
                // Only allow UnixCreateMode for file modes that can create a new file.
                if (options.Mode == FileMode.Truncate || options.Mode == FileMode.Open)
                {
                    throw new ArgumentException(SR.Argument_InvalidUnixCreateMode, nameof(options));
                }
            }

            FileStreamHelpers.SerializationGuard(options.Access);

            _strategy = FileStreamHelpers.ChooseStrategy(
                this, path, options.Mode, options.Access, options.Share, options.BufferSize, options.Options, options.PreallocationSize, options.UnixCreateMode);
        }
Example #22
0
        public AssemblyName(string assemblyName)
            : this()
        {
            ArgumentException.ThrowIfNullOrEmpty(assemblyName);
            if (assemblyName[0] == '\0')
            {
                throw new ArgumentException(SR.Format_StringZeroLength);
            }

            AssemblyNameParser.AssemblyNameParts parts = AssemblyNameParser.Parse(assemblyName);
            _name    = parts._name;
            _version = parts._version;
            _flags   = parts._flags;
            if ((parts._flags & AssemblyNameFlags.PublicKey) != 0)
            {
                _publicKey = parts._publicKeyOrToken;
            }
            else
            {
                _publicKeyToken = parts._publicKeyOrToken;
            }

            if (parts._cultureName != null)
            {
                _cultureInfo = new CultureInfo(parts._cultureName);
            }
        }
Example #23
0
        public virtual byte[] SignData(Stream data, HashAlgorithmName hashAlgorithm)
        {
            ArgumentNullException.ThrowIfNull(data);
            ArgumentException.ThrowIfNullOrEmpty(hashAlgorithm.Name, nameof(hashAlgorithm));

            byte[] hash = HashData(data, hashAlgorithm);
            return(SignHash(hash));
        }
Example #24
0
        /// <summary>
        /// ctor.
        /// </summary>
        /// <param name="contentType">Unparsed value of the Content-Type header.</param>
        public ContentType(string contentType)
        {
            ArgumentException.ThrowIfNullOrEmpty(contentType);

            _isChanged = true;
            _type      = contentType;
            ParseValue();
        }
Example #25
0
        public static void WriteAllBytes(string path, byte[] bytes)
        {
            ArgumentException.ThrowIfNullOrEmpty(path);
            ArgumentNullException.ThrowIfNull(bytes);

            using SafeFileHandle sfh = OpenHandle(path, FileMode.Create, FileAccess.Write, FileShare.Read);
            RandomAccess.WriteAtOffset(sfh, bytes, 0);
        }
Example #26
0
        internal void SetContentFromFile(string fileName, string?mediaType)
        {
            ArgumentException.ThrowIfNullOrEmpty(fileName);

            Stream stream = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read);

            _part.SetContent(stream, null, mediaType);
        }
Example #27
0
        public static Task WriteAllBytesAsync(string path, byte[] bytes, CancellationToken cancellationToken = default(CancellationToken))
        {
            ArgumentException.ThrowIfNullOrEmpty(path);
            ArgumentNullException.ThrowIfNull(bytes);

            return(cancellationToken.IsCancellationRequested
                ? Task.FromCanceled(cancellationToken)
                : Core(path, bytes, cancellationToken));
Example #28
0
 internal static void VerifyValidPath(string path, string argName)
 {
     ArgumentException.ThrowIfNullOrEmpty(path, argName);
     if (path.Contains('\0'))
     {
         throw new ArgumentException(SR.Argument_InvalidPathChars, argName);
     }
 }
        /// <summary>
        /// Adds a Relative Distinguished Name attribute identified by an OID.
        /// </summary>
        /// <param name="oidValue">The OID of the attribute.</param>
        /// <param name="value">The value of the attribute.</param>
        /// <param name="stringEncodingType">
        /// The encoding type to use when encoding the <paramref name="value" />
        /// in to the attribute.
        /// </param>
        /// <exception cref="ArgumentNullException">
        /// <paramref name="oidValue" /> or <paramref name="value" /> is <see langword="null" />.
        /// </exception>
        /// <exception cref="ArgumentException">
        /// <para>
        ///   <paramref name="oidValue" /> is an empty string or not a valid OID.
        /// </para>
        /// <para>-or-</para>
        /// <para>
        ///   <paramref name="stringEncodingType" /> is not a type for character strings.
        /// </para>
        /// <para>-or-</para>
        /// <para>
        ///   <paramref name="value" /> is not encodable as defined by <paramref name="stringEncodingType" />.
        /// </para>
        /// </exception>
        public void Add(string oidValue, string value, UniversalTagNumber?stringEncodingType = null)
        {
            ArgumentNullException.ThrowIfNull(value);
            ArgumentException.ThrowIfNullOrEmpty(oidValue);

            UniversalTagNumber tag = GetAndValidateTagNumber(stringEncodingType);

            EncodeComponent(oidValue, value, tag);
        }
        /// <summary>
        /// Adds a locality name attribute.
        /// </summary>
        /// <param name="localityName">The locality name to add.</param>
        /// <exception cref="ArgumentNullException">
        /// <paramref name="localityName" /> is <see langword="null" />.
        /// </exception>
        /// <exception cref="ArgumentException">
        /// <paramref name="localityName" /> is empty.
        /// </exception>
        /// <remarks>
        /// This encodes an attribute with the OID 2.5.4.7 as a UTF8String.
        /// </remarks>
        public void AddLocalityName(string localityName)
        {
            // ITU T-REC X.520 Annex A:
            // id-at-localityName
            // WITH SYNTAX UnboundedDirectoryString

            ArgumentException.ThrowIfNullOrEmpty(localityName);
            EncodeComponent(Oids.LocalityName, localityName, UniversalTagNumber.UTF8String);
        }