• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

C# IO.FileNotFoundException类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了C#中System.IO.FileNotFoundException的典型用法代码示例。如果您正苦于以下问题:C# FileNotFoundException类的具体用法?C# FileNotFoundException怎么用?C# FileNotFoundException使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。



FileNotFoundException类属于System.IO命名空间,在下文中一共展示了FileNotFoundException类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的C#代码示例。

示例1: ProcessRecord

 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);
     }
 }
开发者ID:nickchal,项目名称:pash,代码行数:60,代码来源:TestModuleManifestCommand.cs


示例2: FileNotFoundLog

 public static void FileNotFoundLog(FileNotFoundException e)
 {
     List<string> log = new List<string>();
     log.Add("FileNotFoundError");
     log.Add(e.Message);
     Errorlogs.PrintLogs(log);
 }
开发者ID:jonatanschneider,项目名称:CCLI_to_TXT,代码行数:7,代码来源:Errorlogs.cs


示例3: FindPackagesByIdAsync

        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;
        }
开发者ID:henghu-bai,项目名称:dnx,代码行数:32,代码来源:KpmPackageFolder.cs


示例4: HandleException

        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);
            }
        }
开发者ID:wallymathieu,项目名称:Prolog.NET,代码行数:29,代码来源:CommonExceptionHandlers.cs


示例5: AdditionalInfoTest

        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]);
            }
        }
开发者ID:jmeckley,项目名称:Enterprise-Library-5.0,代码行数:30,代码来源:ExceptionFormatterFixture.cs


示例6: CreateFileNotFoundErrorRecord

		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;
		}
开发者ID:nickchal,项目名称:pash,代码行数:7,代码来源:SecurityUtils.cs


示例7: DisplayErrorMessagebox

        /// <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
            );
        }
开发者ID:vandango,项目名称:MovieMatic,代码行数:38,代码来源:ErrorHandler.cs


示例8: ValidateDirectory

        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;
            }
        }
开发者ID:CenturionFox,项目名称:attribute-common,代码行数:32,代码来源:FileUtility.cs


示例9: Remove

 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);
     }
 }
开发者ID:pritesh-mandowara-sp,项目名称:DecompliedDotNetLibraries,代码行数:8,代码来源:SingleItemRequestCache.cs


示例10: GetFusionLog_Pass

		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
		}
开发者ID:KonajuGames,项目名称:SharpLang,代码行数:8,代码来源:FileNotFoundExceptionCas.cs


示例11: NoRestriction

		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");
		}
开发者ID:KonajuGames,项目名称:SharpLang,代码行数:10,代码来源:FileNotFoundExceptionCas.cs


示例12: Store

 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;
 }
开发者ID:pritesh-mandowara-sp,项目名称:DecompliedDotNetLibraries,代码行数:10,代码来源:SingleItemRequestCache.cs


示例13: Retrieve

 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;
 }
开发者ID:pritesh-mandowara-sp,项目名称:DecompliedDotNetLibraries,代码行数:10,代码来源:SingleItemRequestCache.cs


示例14: ShowDownloadToolFile

        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;
        }
开发者ID:barrett2474,项目名称:CMS2,代码行数:54,代码来源:Common.cs


示例15: GetYarnCommandPath

 /// <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;
 }
开发者ID:beomyeol,项目名称:reef,代码行数:15,代码来源:YarnCommandLineEnvironment.cs


示例16: FullRestriction

		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");
		}
开发者ID:KonajuGames,项目名称:SharpLang,代码行数:11,代码来源:FileNotFoundExceptionCas.cs


示例17: Constructor1

		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");
		}
开发者ID:Profit0004,项目名称:mono,代码行数:11,代码来源:FileNotFoundExceptionTest.cs


示例18: HandleConnection

        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);
        }
开发者ID:konradsikorski,项目名称:smartCAML,代码行数:11,代码来源:ExceptionHandler.cs


示例19: Constructor2_Message_Null

		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");
		}
开发者ID:Profit0004,项目名称:mono,代码行数:12,代码来源:FileNotFoundExceptionTest.cs


示例20: GetAdviceForUser_ReturnsIntroTextAsFirstLine_Always

        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]);
        }
开发者ID:kurattila,项目名称:Cider-x64,代码行数:12,代码来源:MissingPreloadException_Test.cs



注:本文中的System.IO.FileNotFoundException类示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
C# IO.FileSecurityState类代码示例发布时间:2022-05-26
下一篇:
C# IO.FileInfo类代码示例发布时间:2022-05-26
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap