public void AdditionalInfoTest() { StringBuilder sb = new StringBuilder(); StringWriter writer = new StringWriter(sb); Exception exception = new FileNotFoundException(fileNotFoundMessage, theFile); TextExceptionFormatter formatter = new TextExceptionFormatter(writer, exception); formatter.Format(); if (string.Compare(permissionDenied, formatter.AdditionalInfo[machineName]) != 0) { Assert.AreEqual(Environment.MachineName, formatter.AdditionalInfo[machineName]); } DateTime minimumTime = DateTime.UtcNow.AddMinutes(-1); DateTime loggedTime = DateTime.Parse(formatter.AdditionalInfo[timeStamp]); if (DateTime.Compare(minimumTime, loggedTime) > 0) { Assert.Fail(loggedTimeStampFailMessage); } Assert.AreEqual(AppDomain.CurrentDomain.FriendlyName, formatter.AdditionalInfo[appDomainName]); Assert.AreEqual(Thread.CurrentPrincipal.Identity.Name, formatter.AdditionalInfo[threadIdentity]); if (string.Compare(permissionDenied, formatter.AdditionalInfo[windowsIdentity]) != 0) { Assert.AreEqual(WindowsIdentity.GetCurrent().Name, formatter.AdditionalInfo[windowsIdentity]); } }
public static void FileNotFoundLog(FileNotFoundException e) { List<string> log = new List<string>(); log.Add("FileNotFoundError"); log.Add(e.Message); Errorlogs.PrintLogs(log); }
public static void ValidateDirectory(ProviderInfo provider, string directory) { validateFileSystemPath(provider, directory); if (!Directory.Exists(directory)) { Exception exception; if (File.Exists(directory)) { exception = new InvalidOperationException($"{directory} is not a directory."); ExceptionHelper.SetUpException( ref exception, ERR_NO_DIRECTORY, ErrorCategory.InvalidOperation, directory); } else { exception = new FileNotFoundException( $"The directory {directory} could not be found."); ExceptionHelper.SetUpException( ref exception, ERR_NO_DIRECTORY, ErrorCategory.InvalidData, directory); } throw exception; } }
public static void HandleException(Window window, FileNotFoundException ex) { try { string fileName = Path.GetFileName(ex.FileName); string message = string.Format(Properties.Resources.MessageFileNotFoundException, fileName); TaskDialog dialog = new TaskDialog(); dialog.InstructionText = message; //dialog.Text dialog.Icon = TaskDialogStandardIcon.Error; dialog.StandardButtons = TaskDialogStandardButtons.Ok; dialog.DetailsExpandedText = ex.Message; dialog.Caption = App.Current.ApplicationTitle; if (window != null) { dialog.OwnerWindowHandle = new WindowInteropHelper(window).Handle; } dialog.Show(); } catch (PlatformNotSupportedException) { MessageBox.Show(ex.Message); } }
internal static ErrorRecord CreateFileNotFoundErrorRecord(string resourceStr, string errorId, object[] args) { string str = StringUtil.Format(resourceStr, args); FileNotFoundException fileNotFoundException = new FileNotFoundException(str); ErrorRecord errorRecord = new ErrorRecord(fileNotFoundException, errorId, ErrorCategory.ObjectNotFound, null); return errorRecord; }
/// <summary> /// Display a error messagebox /// </summary> /// <param name="ex">The FileNotFoundException exception</param> public static void DisplayErrorMessagebox(FileNotFoundException ex) { StringBuilder str = new StringBuilder(); str.Append("ERROR\n"); str.Append("Quelle: " + ex.Source + "\n"); str.Append("Fehlermeldung: " + ex.Message + "\n"); str.Append("StackTrace: " + ex.StackTrace + "\n"); str.Append("\n"); if(ex.InnerException != null) { str.Append("INNER EXCEPTION\n"); str.Append("Quelle: " + ex.InnerException.Source + "\n"); str.Append("Fehlermeldung: " + ex.InnerException.Message + "\n"); str.Append("StackTrace: " + ex.InnerException.StackTrace + "\n"); if(ex.InnerException.InnerException != null) { str.Append("\n"); str.Append("INNER EXCEPTION - INNER EXCEPTION\n"); str.Append("Quelle: " + ex.InnerException.InnerException.Source + "\n"); str.Append("Fehlermeldung: " + ex.InnerException.InnerException.Message + "\n"); str.Append("StackTrace: " + ex.InnerException.InnerException.StackTrace + "\n"); } } str.Append(""); MessageBox.Show( str.ToString(), "MovieMatic", MessageBoxButtons.OK, MessageBoxIcon.Error ); }
public Task<IEnumerable<PackageInfo>> FindPackagesByIdAsync(string id) { if (_ignored) { return Task.FromResult(Enumerable.Empty<PackageInfo>()); } if (Directory.Exists(Source)) { return Task.FromResult(_repository.FindPackagesById(id).Select(p => new PackageInfo { Id = p.Id, Version = p.Version })); } var exception = new FileNotFoundException( message: string.Format("The local package source {0} doesn't exist", Source), fileName: Source); if (_ignoreFailure) { _reports.Information.WriteLine(string.Format("Warning: FindPackagesById: {1}\r\n {0}", exception.Message, id).Yellow().Bold()); _ignored = true; return Task.FromResult(Enumerable.Empty<PackageInfo>()); } _reports.Error.WriteLine(string.Format("Error: FindPackagesById: {1}\r\n {0}", exception.Message, id).Red().Bold()); throw exception; }
protected override void ProcessRecord() { ProviderInfo provider = null; Collection<string> resolvedProviderPathFromPSPath; try { if (base.Context.EngineSessionState.IsProviderLoaded(base.Context.ProviderNames.FileSystem)) { resolvedProviderPathFromPSPath = base.SessionState.Path.GetResolvedProviderPathFromPSPath(this._path, out provider); } else { resolvedProviderPathFromPSPath = new Collection<string> { this._path }; } } catch (ItemNotFoundException) { FileNotFoundException exception = new FileNotFoundException(StringUtil.Format(Modules.ModuleNotFound, this._path)); ErrorRecord errorRecord = new ErrorRecord(exception, "Modules_ModuleNotFound", ErrorCategory.ResourceUnavailable, this._path); base.WriteError(errorRecord); return; } if (!provider.NameEquals(base.Context.ProviderNames.FileSystem)) { throw InterpreterError.NewInterpreterException(this._path, typeof(RuntimeException), null, "FileOpenError", ParserStrings.FileOpenError, new object[] { provider.FullName }); } if ((resolvedProviderPathFromPSPath != null) && (resolvedProviderPathFromPSPath.Count >= 1)) { if (resolvedProviderPathFromPSPath.Count > 1) { throw InterpreterError.NewInterpreterException(resolvedProviderPathFromPSPath, typeof(RuntimeException), null, "AmbiguousPath", ParserStrings.AmbiguousPath, new object[0]); } string path = resolvedProviderPathFromPSPath[0]; ExternalScriptInfo scriptInfo = null; if (System.IO.Path.GetExtension(path).Equals(".psd1", StringComparison.OrdinalIgnoreCase)) { string str5; scriptInfo = base.GetScriptInfoForFile(path, out str5, false); PSModuleInfo sendToPipeline = base.LoadModuleManifest(scriptInfo, ModuleCmdletBase.ManifestProcessingFlags.WriteWarnings | ModuleCmdletBase.ManifestProcessingFlags.WriteErrors, null, null); if (sendToPipeline != null) { base.WriteObject(sendToPipeline); } } else { InvalidOperationException exception3 = new InvalidOperationException(StringUtil.Format(Modules.InvalidModuleManifestPath, path)); ErrorRecord record3 = new ErrorRecord(exception3, "Modules_InvalidModuleManifestPath", ErrorCategory.InvalidArgument, this._path); base.ThrowTerminatingError(record3); } } else { FileNotFoundException exception2 = new FileNotFoundException(StringUtil.Format(Modules.ModuleNotFound, this._path)); ErrorRecord record2 = new ErrorRecord(exception2, "Modules_ModuleNotFound", ErrorCategory.ResourceUnavailable, this._path); base.WriteError(record2); } }
internal override void Remove(string key) { if (!this.TryRemove(key)) { FileNotFoundException innerException = new FileNotFoundException(null, key); throw new IOException(SR.GetString("net_cache_retrieve_failure", new object[] { innerException.Message }), innerException); } }
public void GetFusionLog_Pass () { FileNotFoundException fle = new FileNotFoundException ("message", "filename"); Assert.AreEqual ("message", fle.Message, "Message"); Assert.AreEqual ("filename", fle.FileName, "FileName"); Assert.IsNull (fle.FusionLog, "FusionLog"); // note: ToString doesn't work in this case }
public void NoRestriction () { FileNotFoundException fle = new FileNotFoundException ("message", "filename", new FileNotFoundException ("inner message", "inner filename")); Assert.AreEqual ("message", fle.Message, "Message"); Assert.AreEqual ("filename", fle.FileName, "FileName"); Assert.IsNull (fle.FusionLog, "FusionLog"); Assert.IsNotNull (fle.ToString (), "ToString"); }
internal override Stream Store(string key, long contentLength, DateTime expiresUtc, DateTime lastModifiedUtc, TimeSpan maxStale, StringCollection entryMetadata, StringCollection systemMetadata) { Stream stream; if (!this.TryStore(key, contentLength, expiresUtc, lastModifiedUtc, maxStale, entryMetadata, systemMetadata, out stream)) { FileNotFoundException innerException = new FileNotFoundException(null, key); throw new IOException(SR.GetString("net_cache_retrieve_failure", new object[] { innerException.Message }), innerException); } return stream; }
internal override Stream Retrieve(string key, out RequestCacheEntry cacheEntry) { Stream stream; if (!this.TryRetrieve(key, out cacheEntry, out stream)) { FileNotFoundException innerException = new FileNotFoundException(null, key); throw new IOException(SR.GetString("net_cache_retrieve_failure", new object[] { innerException.Message }), innerException); } return stream; }
public static bool ShowDownloadToolFile(HttpResponse httpResponse, NameValueCollection queryString, CommonUtils.AppSettingKey settingKey, out Exception message) { try { string fileName = queryString["DownloadToolFile"]; if (string.IsNullOrEmpty(fileName)) { message = new Exception("Query string 'DownloadToolFile' missing from url."); return false; } if (!File.Exists(fileName)) { message = new FileNotFoundException(string.Format(@"Failed to find file '{0}'. Please ask your administrator to check whether the folder exists.", fileName)); return false; } httpResponse.Clear(); httpResponse.ClearContent(); //Response.OutputStream.f httpResponse.BufferOutput = true; httpResponse.ContentType = "application/unknown"; httpResponse.AddHeader("Content-Disposition", string.Format("attachment; filename=\"{0}\"", Path.GetFileName(fileName))); byte[] fileContent = File.ReadAllBytes(fileName); BinaryWriter binaryWriter = new BinaryWriter(httpResponse.OutputStream); binaryWriter.Write(fileContent, 0, fileContent.Length); binaryWriter.Flush(); binaryWriter.Close(); var dirName = Path.GetDirectoryName(fileName); if (dirName != null) { //Delete any files that are older than 1 hour Directory.GetFiles(dirName) .Select(f => new FileInfo(f)) .Where(f => f.CreationTime < DateTime.Now.AddHours(-1)) .ToList() .ForEach(f => f.Delete()); } } catch (Exception ex) { message = ex; return false; } message = null; return true; }
/// <summary> /// Returns the full Path to the `yarn.cmd` file. /// </summary> /// <returns>The full Path to the `yarn.cmd` file.</returns> private string GetYarnCommandPath() { var result = Path.Combine(GetHadoopHomePath(), "bin", "yarn.cmd"); if (!File.Exists(result)) { var ex = new FileNotFoundException("Couldn't find yarn.cmd", result); Exceptions.Throw(ex, Logger); throw ex; } return result; }
public void FullRestriction () { FileNotFoundException fle = new FileNotFoundException ("message", "filename", new FileNotFoundException ("inner message", "inner filename")); Assert.AreEqual ("message", fle.Message, "Message"); Assert.AreEqual ("filename", fle.FileName, "FileName"); Assert.IsNull (fle.FusionLog, "FusionLog"); // ToString doesn't work in this case and strangely throws a FileNotFoundException Assert.IsNotNull (fle.ToString (), "ToString"); }
private static void HandleConnection(FileNotFoundException ex) { Log.Error(ex); StatusNotification.Notify("Connection failed"); if (ex.Message.Contains("Microsoft.SharePoint")) MessageBox.Show("Could not load file or assembly 'Microsoft.SharePoint, Version=15.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c'.\n\n" + "Make shure you are running application on SharePoint sever or change the connection type to 'Client' in 'advance settings'.", "Connection failed", MessageBoxButton.OK, MessageBoxImage.Information); else MessageBox.Show(ex.Message, "Connection failed", MessageBoxButton.OK, MessageBoxImage.Information); }
public void Constructor1 () { FileNotFoundException fnf = new FileNotFoundException (); Assert.IsNotNull (fnf.Data, "#1"); Assert.IsNull (fnf.FileName, "#2"); Assert.IsNull (fnf.InnerException, "#3"); Assert.IsNotNull (fnf.Message, "#4"); // Unable to find the specified file Assert.IsNull (fnf.FusionLog, "#5"); Assert.IsTrue (fnf.ToString ().StartsWith (fnf.GetType().FullName), "#6"); }
public void Constructor2_Message_Null () { FileNotFoundException fnf = new FileNotFoundException ((string) null); Assert.IsNotNull (fnf.Data, "#1"); Assert.IsNull (fnf.FileName, "#2"); Assert.IsNull (fnf.InnerException, "#3"); Assert.IsNull (fnf.Message, "#4"); Assert.IsNull (fnf.FusionLog, "#5"); Assert.AreEqual (fnf.GetType ().FullName + ": ", fnf.ToString (), "#6"); }
public void GetAdviceForUser_ReturnsIntroTextAsFirstLine_Always() { var fileNotFoundException = new FileNotFoundException("message about missing styles", "dummyAssemblyStyles.dll"); var xamlParseException = new XamlParseException("", fileNotFoundException); var targetInvocationException = new TargetInvocationException(xamlParseException); var missingPreloadException = new MissingPreloadException("", targetInvocationException); string adviceForUser = missingPreloadException.GetAdviceForUser(); string[] lines = adviceForUser.Split(new string[] { Environment.NewLine }, StringSplitOptions.None); Assert.AreEqual(MissingPreloadException.IntroPartOfAdvice, lines[0]); }
/// <summary> /// Initializes XmlEmailContentProvider /// </summary> /// <param name="TemplateFolder">Full path to the Template Folder</param> public XmlEmailContentProvider(string TemplateFolder) { if (!Path.IsPathRooted(TemplateFolder)) throw new EmailServiceException("Full path to the Template Folder must be provided."); if (!File.Exists(TemplateFolder)) { FileNotFoundException fnfe = new FileNotFoundException("Template folder not found", TemplateFolder); throw new EmailServiceException(fnfe, "Template folder specified does not exist."); } templateFolder = TemplateFolder; }
protected bool CheckFileExists(string file) { if (!File.Exists(file)) { this.WriteVerbose("Filename: {0}",file); this.WriteVerbose("Abs Filename: {0}", Path.GetFullPath(file)); var exc = new FileNotFoundException(file); var er = new SMA.ErrorRecord(exc, "FILE_NOT_FOUND", SMA.ErrorCategory.ResourceUnavailable, null); this.WriteError(er); return false; } return true; }
protected void CheckFileUploadStatus(string response) { UploadInfo info = DeserializeUploadResponse(response); if (info != null) { string errorMessage = HttpUtility.HtmlDecode(info.ErrorMessage); HttpUploadCode code = (HttpUploadCode) info.StatusCode; switch (code) { case HttpUploadCode.Ok: { break; } case HttpUploadCode.Unauthorized: { Exception = new UnauthorizedException(errorMessage); break; } case HttpUploadCode.NotFound: { Exception = new FileNotFoundException(errorMessage); break; } case HttpUploadCode.FileExists: { Exception = new FileExistsException(errorMessage); break; } case HttpUploadCode.BlockedFile: { Exception = new FileBlockedException(errorMessage); break; } case HttpUploadCode.FileLocked: { Exception = new FileLockedException(errorMessage); break; } case HttpUploadCode.DeleteFailed: { Exception = new DeleteFailedException(errorMessage); break; } default: { Exception = new UploadException(string.Format(CultureInfo.InvariantCulture, "Invalid status code : {0}", code)); break; } } } }
protected static object CreateInstanceFromType(string typeName) { string type = typeName; IEnumerable <Type> comTypes = null; try { //var assembly = Assembly.GetExecutingAssembly(); var comAssembly = System.Reflection.Assembly.Load("Com"); comTypes = ((Assembly)comAssembly).GetTypes(); // If at least one type cannot be loaded then there will be an exception } catch (ReflectionTypeLoadException ex) { comTypes = ex.Types.Where(t => t != null); // Just to learn which other assembly could not be loaded StringBuilder sb = new StringBuilder(); foreach (Exception exSub in ex.LoaderExceptions) { sb.AppendLine(exSub.Message); System.IO.FileNotFoundException exFileNotFound = exSub as System.IO.FileNotFoundException; if (exFileNotFound != null) { if (!string.IsNullOrEmpty(exFileNotFound.FusionLog)) { sb.AppendLine("Fusion Log:"); sb.AppendLine(exFileNotFound.FusionLog); } } sb.AppendLine(); } string errorMessage = sb.ToString(); } var klass = comTypes.First(t => t != null && t.Name == type); object obj = Activator.CreateInstance(klass); // Alternatives: //object obj = Activator.CreateInstance(Type.GetType(full_type)); //object obj = Activator.CreateInstance(null, full_type).Unwrap(); // Get a list of derived types: assembly.GetTypes().Where(baseType.IsAssignableFrom).Where(t => baseType != t); if (obj == null) { throw new NotImplementedException("Cannot instantiate this object type"); } return(obj); }
static FileUtils() { FileNotFoundMessage = new FileNotFoundException().Message; Dictionary<Char, Char> bad = new Dictionary<Char, Char>(); foreach (char ch in new char[] { '/', '\\', ':', '*', '?', '"', '<', '>', '|' }) bad[ch] = ch; foreach (char ch in Path.GetInvalidFileNameChars()) bad[ch] = ch; List<Char> badChars = new List<Char>(bad.Keys); badChars.Sort(); IllegalFileNameChars = badChars.ToArray(); }
public void Constructor2_Message_Empty () { FileNotFoundException fnf = new FileNotFoundException (string.Empty); #if NET_2_0 Assert.IsNotNull (fnf.Data, "#1"); #endif Assert.IsNull (fnf.FileName, "#2"); Assert.IsNull (fnf.InnerException, "#3"); Assert.IsNotNull (fnf.Message, "#4"); Assert.AreEqual (string.Empty, fnf.Message, "#5"); Assert.IsNull (fnf.FusionLog, "#6"); Assert.AreEqual (fnf.GetType ().FullName + ": ", fnf.ToString (), "#7"); }
public void ReflectionTypeLoadExceptionSupport() { FileNotFoundException ex1 = new FileNotFoundException(); OutOfMemoryException ex2 = new OutOfMemoryException(); ReflectionTypeLoadException wrapper = new ReflectionTypeLoadException(new Type[] { typeof(FakeRaygunClient), typeof(WrapperException) }, new Exception[] { ex1, ex2 }); RaygunErrorMessage message = RaygunErrorMessageBuilder.Build(wrapper); Assert.AreEqual(2, message.InnerErrors.Count()); Assert.AreEqual("System.IO.FileNotFoundException", message.InnerErrors[0].ClassName); Assert.AreEqual("System.OutOfMemoryException", message.InnerErrors[1].ClassName); Assert.IsTrue(message.InnerErrors[0].Data["Type"].ToString().Contains("FakeRaygunClient")); Assert.IsTrue(message.InnerErrors[1].Data["Type"].ToString().Contains("WrapperException")); }
/// <summary>Anies the given request.</summary> /// /// <exception cref="ArgumentNullException">Thrown when one or more required arguments are null.</exception> /// <exception cref="FileNotFoundException">Thrown when the requested file is not present.</exception> /// <exception cref="HttpError"> Thrown when a HTTP error error condition occurs.</exception> /// /// <param name="request">The request.</param> /// /// <returns>An object.</returns> public object Any(HttpError request) { if (request.Type.IsNullOrEmpty()) throw new ArgumentNullException("Type"); var ex = new Exception(request.Message); switch (request.Type) { case "FileNotFoundException": ex = new FileNotFoundException(request.Message); break; } if (!request.StatusCode.HasValue) throw ex; var httpStatus = (HttpStatusCode)request.StatusCode.Value; throw new Common.Web.HttpError(httpStatus, ex); }
public void Constructor2 () { FileNotFoundException fnf = new FileNotFoundException ("message"); #if NET_2_0 Assert.IsNotNull (fnf.Data, "#1"); #endif Assert.IsNull (fnf.FileName, "#2"); Assert.IsNull (fnf.InnerException, "#3"); Assert.IsNotNull (fnf.Message, "#4"); Assert.AreEqual ("message", fnf.Message, "#5"); Assert.IsNull (fnf.FusionLog, "#6"); #if TARGET_JVM Assert.IsTrue(fnf.ToString().StartsWith(fnf.GetType().FullName + ": message"),"#7"); #else Assert.AreEqual (fnf.GetType ().FullName + ": message", fnf.ToString (), "#7"); #endif }
/// <summary> /// Returns the full Path to HADOOP_HOME /// </summary> /// <returns>The full Path to HADOOP_HOME</returns> private string GetHadoopHomePath() { var path = Environment.GetEnvironmentVariable("HADOOP_HOME"); if (string.IsNullOrWhiteSpace(path)) { var ex = new FileNotFoundException("HADOOP_HOME isn't set."); Exceptions.Throw(ex, Logger); throw ex; } var fullPath = Path.GetFullPath(path); if (!Directory.Exists(fullPath)) { var ex = new FileNotFoundException("HADOOP_HOME points to [" + fullPath + "] which doesn't exist."); Exceptions.Throw(ex, Logger); throw ex; } return fullPath; }
public void AdditionalInfoTest() { StringBuilder sb = new StringBuilder(); StringWriter writer = new StringWriter(sb, TestUtility.DefaultCulture); Exception exception = new FileNotFoundException("The file can't be found", "theFile"); TextExceptionFormatter formatter = new TextExceptionFormatter(writer, exception); formatter.Format(); Assert.AreEqual(Environment.MachineName, formatter.AdditionalInfo["MachineName"]); DateTime minimumTime = DateTime.Now.AddMinutes(-1); DateTime loggedTime = DateTime.Parse(formatter.AdditionalInfo["TimeStamp"]); if (DateTime.Compare(minimumTime, loggedTime) > 0) { Assert.Fail("Logged TimeStamp is not within a one minute time window"); } Assert.AreEqual(AppDomain.CurrentDomain.FriendlyName, formatter.AdditionalInfo["AppDomainName"]); Assert.AreEqual(Thread.CurrentPrincipal.Identity.Name, formatter.AdditionalInfo["ThreadIdentity"]); Assert.AreEqual(WindowsIdentity.GetCurrent().Name, formatter.AdditionalInfo["WindowsIdentity"]); }
private static CommonSecurityDescriptor CreateInternal(ResourceType resourceType, bool isContainer, string name, SafeHandle handle, AccessControlSections includeSections, bool createByName, ExceptionFromErrorCode exceptionFromErrorCode, object exceptionContext) { int error; RawSecurityDescriptor rawSD; if (createByName && name == null) { throw new ArgumentNullException(nameof(name)); } else if (!createByName && handle == null) { throw new ArgumentNullException(nameof(handle)); } error = Win32.GetSecurityInfo(resourceType, name, handle, includeSections, out rawSD); if (error != Interop.Errors.ERROR_SUCCESS) { System.Exception exception = null; if (exceptionFromErrorCode != null) { exception = exceptionFromErrorCode(error, name, handle, exceptionContext); } if (exception == null) { if (error == Interop.Errors.ERROR_ACCESS_DENIED) { exception = new UnauthorizedAccessException(); } else if (error == Interop.Errors.ERROR_INVALID_OWNER) { exception = new InvalidOperationException(SR.AccessControl_InvalidOwner); } else if (error == Interop.Errors.ERROR_INVALID_PRIMARY_GROUP) { exception = new InvalidOperationException(SR.AccessControl_InvalidGroup); } else if (error == Interop.Errors.ERROR_INVALID_PARAMETER) { exception = new InvalidOperationException(SR.Format(SR.AccessControl_UnexpectedError, error)); } else if (error == Interop.Errors.ERROR_INVALID_NAME) { exception = new ArgumentException(SR.Argument_InvalidName, nameof(name)); } else if (error == Interop.Errors.ERROR_FILE_NOT_FOUND) { exception = new FileNotFoundException(name); } else if (error == Interop.Errors.ERROR_PATH_NOT_FOUND) { exception = isContainer switch { false => new FileNotFoundException(name), true => new DirectoryNotFoundException(name) }; } else if (error == Interop.Errors.ERROR_NO_SECURITY_ON_OBJECT) { exception = new NotSupportedException(SR.AccessControl_NoAssociatedSecurity); } else if (error == Interop.Errors.ERROR_PIPE_NOT_CONNECTED) { exception = new InvalidOperationException(SR.InvalidOperation_DisconnectedPipe); } else { Debug.Fail($"Win32GetSecurityInfo() failed with unexpected error code {error}"); exception = new InvalidOperationException(SR.Format(SR.AccessControl_UnexpectedError, error)); } } throw exception; } return(new CommonSecurityDescriptor(isContainer, false /* isDS */, rawSD, true)); }
// // Attempts to persist the security descriptor onto the object // private void Persist(string name, SafeHandle handle, AccessControlSections includeSections, object exceptionContext) { WriteLock(); try { int error; SecurityInfos securityInfo = 0; SecurityIdentifier owner = null, group = null; SystemAcl sacl = null; DiscretionaryAcl dacl = null; if ((includeSections & AccessControlSections.Owner) != 0 && _securityDescriptor.Owner != null) { securityInfo |= SecurityInfos.Owner; owner = _securityDescriptor.Owner; } if ((includeSections & AccessControlSections.Group) != 0 && _securityDescriptor.Group != null) { securityInfo |= SecurityInfos.Group; group = _securityDescriptor.Group; } if ((includeSections & AccessControlSections.Audit) != 0) { securityInfo |= SecurityInfos.SystemAcl; if (_securityDescriptor.IsSystemAclPresent && _securityDescriptor.SystemAcl != null && _securityDescriptor.SystemAcl.Count > 0) { sacl = _securityDescriptor.SystemAcl; } else { sacl = null; } if ((_securityDescriptor.ControlFlags & ControlFlags.SystemAclProtected) != 0) { securityInfo = (SecurityInfos)((uint)securityInfo | ProtectedSystemAcl); } else { securityInfo = (SecurityInfos)((uint)securityInfo | UnprotectedSystemAcl); } } if ((includeSections & AccessControlSections.Access) != 0 && _securityDescriptor.IsDiscretionaryAclPresent) { securityInfo |= SecurityInfos.DiscretionaryAcl; // if the DACL is in fact a crafted replaced for NULL replacement, then we will persist it as NULL if (_securityDescriptor.DiscretionaryAcl.EveryOneFullAccessForNullDacl) { dacl = null; } else { dacl = _securityDescriptor.DiscretionaryAcl; } if ((_securityDescriptor.ControlFlags & ControlFlags.DiscretionaryAclProtected) != 0) { securityInfo = unchecked ((SecurityInfos)((uint)securityInfo | ProtectedDiscretionaryAcl)); } else { securityInfo = (SecurityInfos)((uint)securityInfo | UnprotectedDiscretionaryAcl); } } if (securityInfo == 0) { // // Nothing to persist // return; } error = Win32.SetSecurityInfo(_resourceType, name, handle, securityInfo, owner, group, sacl, dacl); if (error != Interop.Errors.ERROR_SUCCESS) { System.Exception exception = null; if (_exceptionFromErrorCode != null) { exception = _exceptionFromErrorCode(error, name, handle, exceptionContext); } if (exception == null) { if (error == Interop.Errors.ERROR_ACCESS_DENIED) { exception = new UnauthorizedAccessException(); } else if (error == Interop.Errors.ERROR_INVALID_OWNER) { exception = new InvalidOperationException(SR.AccessControl_InvalidOwner); } else if (error == Interop.Errors.ERROR_INVALID_PRIMARY_GROUP) { exception = new InvalidOperationException(SR.AccessControl_InvalidGroup); } else if (error == Interop.Errors.ERROR_INVALID_NAME) { exception = new ArgumentException(SR.Argument_InvalidName, nameof(name)); } else if (error == Interop.Errors.ERROR_INVALID_HANDLE) { exception = new NotSupportedException(SR.AccessControl_InvalidHandle); } else if (error == Interop.Errors.ERROR_FILE_NOT_FOUND) { exception = new FileNotFoundException(); } else if (error == Interop.Errors.ERROR_NO_SECURITY_ON_OBJECT) { exception = new NotSupportedException(SR.AccessControl_NoAssociatedSecurity); } else { Debug.Fail($"Unexpected error code {error}"); exception = new InvalidOperationException(SR.Format(SR.AccessControl_UnexpectedError, error)); } } throw exception; } // // Everything goes well, let us clean the modified flags. // We are in proper write lock, so just go ahead // this.OwnerModified = false; this.GroupModified = false; this.AccessRulesModified = false; this.AuditRulesModified = false; } finally { WriteUnlock(); } }
private void Error(object sender, System.IO.FileNotFoundException e) { MessageBox.Show("неправильное заполнение"); }