命令行-需要在C#中模拟异常的帮助吗

本文关键字:异常 模拟 帮助 命令行 | 更新日期: 2023-09-27 18:00:50

我试图模拟一个错误,但我很难完成。我下面的源代码应该查看中的每个驱动器,并找到一个文件夹或文件,其中包含您作为参数传入的。然后,它将发现的内容写入日志文件(.log(中的驱动器(%SystemDrive%(。该代码在我的本地计算机上运行,但当其他人尝试运行它时,他们会收到未授权的AccessException:拒绝访问路径"c:''ARAGOR.log"。出于某种奇怪的原因,这个人无法将结果写入该日志文件,我不明白为什么。有人能看看是否可以模拟这个异常吗。请从命令行或powershell运行此程序。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.Management;
using System.Security.Permissions;
using System.Collections;
/***
 *                                                                                          
 *  Written by:                                                                                          
 *                                                                                          
 *  Description: Look through every single drive to find files with the name <the file that you are look of> (Specify name in the string theString).
 *               All files are then stored in an ArrayList called fileList.
 *  
 *  Notes: If a file does note have the exact name, it will be ignored.
 *         This only finds files with the name you are looking for. Directories will be ignored.
 *                                                                                          
 * 
 * */
namespace FileFinder
{
    class Program
    {
        static ArrayList fileList = new ArrayList();
        static ArrayList folderList = new ArrayList();
        static void Main(string[] args)
        {
            //Console.WriteLine("There are this many args: " + args.Length);
            if(args.Length < 1)
            {
                Console.WriteLine("Too few arguments");
                System.Environment.Exit(1);
            }
            else if(args.Length > 1)
            {
                Console.WriteLine("Too many arguments");
                System.Environment.Exit(1);
            }
            //change the name you search for a specific file name
            //Console.WriteLine("Enter the file name");
            string hostName = System.Net.Dns.GetHostName();
            string theString = args[0];
            foreach (DriveInfo d in DriveInfo.GetDrives())
            {
                string drive = d.Name;
                try
                {
                    Console.WriteLine("Looking in " + drive + " for " + theString);
                    LookForFileInDir(drive, theString);
                }
                catch (Exception e)
                {
                    Console.WriteLine(e.Message);
                }

            }
            //Console.WriteLine("The Host Name is: " + hostName);
            Console.WriteLine("There are " + fileList.Count + " files that were found with the name " + theString);
            Console.WriteLine("There are " + folderList.Count + " folders that were found with the name " + theString);

            var actualPath = Environment.ExpandEnvironmentVariables(@"%SystemDrive%'"+hostName+".log");
            using (System.IO.StreamWriter file = new System.IO.StreamWriter(actualPath ))
            {
                file.WriteLine("bytes't" + "file");
                foreach (string f in fileList)
                {
                    file.WriteLine(f);
                }
                file.WriteLine();
                file.WriteLine("'t" + "folder");
                foreach (string folder in folderList)
                {
                    file.WriteLine(folder);
                }
            }
            Console.WriteLine("Press enter to close...");
            Console.ReadLine();
        }
        /**
         * 
         * Looks for files in directories
         * 
         * */
        static void LookForFileInDir(string folder, string theString)
        {
            string output = "";
            //Console.WriteLine("I am not losing my mind");
            foreach (string file in Directory.GetFiles(folder, "*" + theString + "*.*"))
            {
                //Console.WriteLine("I am not losing my mind");
                if (!IsLink(file))
                {
                    FileInfo info = new FileInfo(file);
                    Console.WriteLine(info.Length + "'t" + file);
                    fileList.Add(info.Length + "'t" + file);
                    output += file;
                }
            }
            foreach (string subDir in Directory.GetDirectories(folder, theString))
            {
                try
                {
                    Console.WriteLine("'t" + subDir);
                    folderList.Add("'t" + subDir);
                }
                //Ignores all shortcuts in a drive
                catch (UnauthorizedAccessException e)
                {
                }
                catch (Exception e)
                {
                    Console.WriteLine(e.Message);
                    output += e.Message;
                }
            }

            foreach (string subDir in Directory.GetDirectories(folder))
            {
                try
                {
                    LookForFileInDir(subDir, theString);
                }
                //Ignores all shortcuts in a drive
                catch (UnauthorizedAccessException e)
                {
                }
                catch (Exception e)
                {
                    Console.WriteLine(e.Message);
                    output += e.Message;
                }
            }
        }
        /// <summary>
        /// Returns whether the given path/file is a link
        /// </summary>
        /// <param name="shortcutFilename"></param>
        /// <returns></returns>
        public static bool IsLink(string shortcutFilename)
        {
            string pathOnly = System.IO.Path.GetDirectoryName(shortcutFilename);
            string filenameOnly = System.IO.Path.GetFileName(shortcutFilename);
            Shell32.Shell shell = new Shell32.Shell();
            Shell32.Folder folder = shell.NameSpace(pathOnly);
            Shell32.FolderItem folderItem = folder.ParseName(filenameOnly);
            if (folderItem != null)
            {
                return folderItem.IsLink;
            }
            return false; // not found
        }
    }
}

命令行-需要在C#中模拟异常的帮助吗

要模拟异常,只需拒绝调试用户对C:''的写入访问

实际上根C:不是一个转储文件的好地方——标准的Windows访问限制在这种情况下是有意义的。在你的位置,我会考虑移动日志文件,即临时文件夹(如我的第一条评论所述(。这应该能解决问题。

然而,如果你坚持保持文件原样,我会确保用管理员权限执行程序。这也应该解决问题。

默认情况下,

命令提示符不使用管理员权限运行。在Windows Vista或更高版本上,在没有管理员权限(或没有禁用UAC和一些安全性(的情况下,C驱动器被锁定,无法写入。

我建议更改日志文件的位置。桌面将是一个很好的地方,你可以使用特殊的文件夹为任何用户放置它。

Environment.GetFolderPath(Environment.SpecialFolder.Desktop)

MSDN提供了其他文件夹选项,如果您的经理想要系统文件夹,但最终用户不能使用提升的权限,则可能需要进行一些抵制。如果可以,请确保他们以管理员身份运行。

我们还可以判断例外是文件夹访问权限,因为:

  1. 这不是因为扩大了环境变量。如果失败,则抛出ArgumentNullException
  2. 异常指向UAC。MSDN介绍了出现此异常的原因:

UnauthorizedAccessException异常通常由以下方法引发包装Windows API调用。为了找出异常的原因,检查异常对象的Message属性的文本。UnauthorizedAccessException使用HRESULT COR_E_UNAUTHORIZEDACCESS,其具有值0x80070005。