public VolumeInfo GetVolumeInformation(string devicePathName)
        {
            StringBuilder volumeName = new StringBuilder(256);
            StringBuilder fileSystem = new StringBuilder(256);

            ErrorModes mode = SetErrorMode(ErrorModes.SEM_FAILCRITICALERRORS);

            try {
                bool success = Kernel32.GetVolumeInformation(devicePathName,
                                                             volumeName, volumeName.Capacity, out uint volumeSerial,
                                                             out uint _, out FileSystemFlags flags, fileSystem, fileSystem.Capacity);
                if (!success)
                {
                    m_Win32Error = Marshal.GetLastWin32Error();
                    return(null);
                }

                return(new VolumeInfo()
                {
                    VolumeLabel = volumeName.ToString(),
                    VolumeSerial = string.Format("{0:X4}-{1:X4}", (volumeSerial & 0xFFFF0000) >> 16, volumeSerial & 0xFFFF),
                    Flags = flags,
                    FileSystem = fileSystem.ToString(),
                });
            } finally {
                SetErrorMode(mode);
            }
        }
Exemple #2
0
        /// <summary>
        /// loads a shared library (on Windows: dynamic link library, *.dll; on Unix: shared object, lib*.so)
        /// </summary>
        /// <param name="LibName"></param>
        /// <returns>library handle, for the use in functions <see cref="LoadSymbol"/> and <see cref="UnloadDynLib"/></returns>
        /// <remarks>
        /// On Windows, this function redirects to the 'LoadLibrary'-function in kernel32.dll;<br/>
        /// On Unix, this function redirects to the 'dlopen'-function in libdl.so;
        /// </remarks>
        /// <param name="errstr">
        /// on success, null;
        /// if call failed (return value is null), an error information provided by the operating system
        /// </param>
        /// <param name="loadGlobal">
        /// only effective on Linux/UNIX systems; if true, a library is loaded with the 'RTDL_GLOBAL' flag:
        /// thereby, it can be used automatically by the operating system to resolve symbols in other libraries.
        /// </param>
        public static DynLibHandle LoadDynLib(string LibName, out string errstr, bool loadGlobal)
        {
            PlatformID plattid = System.Environment.OSVersion.Platform;

            errstr = null;
            DynLibHandle ret;

            switch (plattid)
            {
            case PlatformID.Win32NT:
                // Try to load but suppress ugly dialog box error
                ErrorModes originalMode = SetErrorMode(ErrorModes.SEM_FAILCRITICALERRORS);
                ret.val = LoadLibrary(LibName);
                SetErrorMode(originalMode);

                if (ret.val == IntPtr.Zero)
                {
                    errstr = GetLastWin32Error();
                }
                break;

            case PlatformID.Unix:
                ret.val = dlopen(LibName, loadGlobal ? (2 | 256) : 2);     // 2 == RTLD_NOW, 256 == RTDL_GLOBAL
                if (ret.val == IntPtr.Zero)
                {
                    errstr = _dlerror();
                }
                break;

            default:
                throw new NotImplementedException("Dynamic Library Loading for " + plattid + " is not supported.");
            }
            return(ret);
        }
Exemple #3
0
        private static void InitializeErrorHandling()
        {
            AppDomain.CurrentDomain.UnhandledException += CurrentDomainUnhandledException;
            const ErrorModes desiredErrorModes = ErrorModes.SEM_FAILCRITICALERRORS | ErrorModes.SEM_NOGPFAULTERRORBOX;
            var dwMode = SetErrorMode(desiredErrorModes);

            SetErrorMode(dwMode | desiredErrorModes);
        }
Exemple #4
0
        public ChangeErrorMode(ErrorModes mode)
        {
            _oldMode = (int)ErrorModes.Default;

            if (!IsLinux)
            {
                _oldMode = SetErrorMode((int)mode);
            }
        }
Exemple #5
0
        private static ErrorModes SetErrorModeWithCheck(ErrorModes uMode)
        {
            if (!RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
            {
                throw new PlatformNotSupportedException("Windows only feature yet");
            }

            return(SetErrorMode(uMode));
        }
Exemple #6
0
 internal static void DisableShellModalErrorDialogs()
 {
     if (ApplicationInfo.IsWindows)
     {
         const ErrorModes newErrorMode = ErrorModes.SEM_FAILCRITICALERRORS |
                                         ErrorModes.SEM_NOGPFAULTERRORBOX |
                                         ErrorModes.SEM_NOOPENFILEERRORBOX;
         SetErrorMode(newErrorMode);
     }
 }
        public System.IO.FileAttributes GetFileAttributes(string pathName)
        {
            ErrorModes mode = SetErrorMode(ErrorModes.SEM_FAILCRITICALERRORS);

            try {
                return((System.IO.FileAttributes)Kernel32.GetFileAttributes(pathName));
            } finally {
                SetErrorMode(mode);
            }
        }
        public int GetDriveType(string devicePathName)
        {
            ErrorModes mode = SetErrorMode(ErrorModes.SEM_FAILCRITICALERRORS);

            try {
                return(Kernel32.GetDriveType(devicePathName));
            } finally {
                SetErrorMode(mode);
            }
        }
 public ChangeErrorMode(ErrorModes mode)
 {
     try
     {
         oldMode = SetErrorMode((int)mode);
     }
     catch (Exception ex) when(ex is EntryPointNotFoundException || ex is DllNotFoundException)
     {
         oldMode = (int)mode;
     }
 }
Exemple #10
0
 public ChangeErrorMode(ErrorModes mode)
 {
     try
     {
         oldMode = SetErrorMode((int)mode);
     }
     catch (EntryPointNotFoundException)
     {
         oldMode = (int)mode;
     }
 }
Exemple #11
0
        /**
         * Display all available interfaces that have at least one device available.
         *
         * @return List of the detected interfaces.
         */
        static HTuple showAvailableInterfaces()
        {
            HTuple deviceInfo, deviceValue, interfacesAll, temp;
            HTuple interfaces = new HTuple();

            Console.WriteLine(System.Environment.NewLine +
                              "Detect and show all available interfaces..." +
                              System.Environment.NewLine);
            interfacesAll = HInfo.GetParamInfo("info_framegrabber", "Name", "values");

            if (interfacesAll.Length > 0)
            {
                Console.WriteLine("Available interfaces:");
            }
            else
            {
                Console.WriteLine("Found no interfaces.");
                return(interfaces);
            }

            ErrorModes errorMode = GetErrorMode();

            // Disable error dialog boxes on interface detection.
            SetErrorMode(ErrorModes.SEM_FAILCRITICALERRORS |
                         ErrorModes.SEM_NOGPFAULTERRORBOX |
                         ErrorModes.SEM_NOOPENFILEERRORBOX);

            for (int i = 0; i < interfacesAll.Length; i++)
            {
                try
                {
                    temp       = interfacesAll.TupleSelect(i);
                    deviceInfo = HInfo.InfoFramegrabber(temp.S.ToString(), "device",
                                                        out deviceValue);
                }
                catch (HalconException)
                {
                    // Interface not available.
                    continue;
                }

                if (deviceValue.Length > 0)
                {
                    interfaces.Append(interfacesAll.TupleSelect(i));
                    Console.WriteLine(interfaces.Length + ")" +
                                      interfacesAll.TupleSelect(i).S.ToString());
                }
            }

            // Restore previous error mode.
            SetErrorMode(errorMode);

            return(interfaces);
        }
        public DiskFreeSpace GetDiskFreeSpace(string devicePathName)
        {
            DiskFreeSpace space = new DiskFreeSpace()
            {
                SectorsPerCluster = 0,
                BytesPerSector    = 0,
                UserBytesFree     = 0,
                TotalBytesFree    = 0,
                TotalBytes        = 0
            };

            ErrorModes mode = SetErrorMode(ErrorModes.SEM_FAILCRITICALERRORS);

            try {
                bool successEx = GetDiskFreeSpaceEx(devicePathName, out ulong freeBytes, out ulong totalBytes, out ulong totalFreeBytes);
                if (!successEx)
                {
                    m_Win32Error = Marshal.GetLastWin32Error();
                }
                else
                {
                    space.UserBytesFree  = (long)freeBytes;
                    space.TotalBytes     = (long)totalBytes;
                    space.TotalBytesFree = (long)totalFreeBytes;
                }

                bool success = Kernel32.GetDiskFreeSpace(devicePathName, out int sectorsPerCluster, out int bytesPerSector, out int _, out int _);
                if (!success)
                {
                    m_Win32Error = Marshal.GetLastWin32Error();
                }
                else
                {
                    space.SectorsPerCluster = sectorsPerCluster;
                    space.BytesPerSector    = bytesPerSector;
                }

                if (!success && !successEx)
                {
                    return(null);
                }
                return(space);
            } finally {
                SetErrorMode(mode);
            }
        }
        public SafeHandle CreateFileFromDevice(string pathName)
        {
            ErrorModes mode = SetErrorMode(ErrorModes.SEM_FAILCRITICALERRORS);

            try {
                SafeObjectHandle hDevice = CreateFile(pathName, 0,
                                                      FileShare.FILE_SHARE_READ | FileShare.FILE_SHARE_WRITE, IntPtr.Zero, CreationDisposition.OPEN_EXISTING,
                                                      0, SafeObjectHandle.Null);
                if (hDevice == null || hDevice.IsInvalid)
                {
                    m_Win32Error = Marshal.GetLastWin32Error();
                    int e = Marshal.GetHRForLastWin32Error();
                    Marshal.ThrowExceptionForHR(e, INVALID_HANDLE_VALUE);
                    throw new System.IO.IOException("Couldn't open device for reading", e);
                }
                return(hDevice);
            } finally {
                SetErrorMode(mode);
            }
        }
        public ChangeErrorMode(ErrorModes mode)
        {
            try
            {
                this.oldMode = SetErrorMode((int)mode);
            }
            catch (Exception ex) when(ex is EntryPointNotFoundException or DllNotFoundException)
            {
                this.oldMode = (int)mode;
            }
        }

        void IDisposable.Dispose()
        {
            try
            {
                SetErrorMode(this.oldMode);
            }
            catch (Exception ex) when(ex is EntryPointNotFoundException or DllNotFoundException)
            {
                // NOTE: Mono doesn't support DllImport("kernel32.dll") and its SetErrorMode method, obviously. @asbjornu
            }
        }
Exemple #15
0
 public ErrorModeContext(ErrorModes mode)
 {
     _oldMode = SetErrorMode((int)mode);
 }
Exemple #16
0
 private static extern ErrorModes SetErrorMode(ErrorModes newMode);
Exemple #17
0
 /// <summary> Инициализирует новый экземпляр структуры <see cref="ChangeErrorMode"/>, устанавливая режим обработки ошибок. </summary>
 /// <param name="mode"> Режим. </param>
 public ChangeErrorMode(ErrorModes mode)
 {
     oldMode = ErrorModes.Default; // https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/compiler-messages/cs0188
     oldMode = SetErrorModeWithCheck(mode);
 }
 private static extern ErrorModes SetErrorMode(ErrorModes modes);
Exemple #19
0
 public ChangeErrorMode(ErrorModes mode)
 {
     oldMode = SetErrorMode((int)mode);
 }
Exemple #20
0
 private static extern ErrorModes SetErrorMode(ErrorModes newMode);
Exemple #21
0
 public static extern ErrorModes SetErrorMode(ErrorModes newMode);
 public ErrorModeContext(ErrorModes mode) {
     _oldMode = SetErrorMode((int) mode);
 }
 public ErrorModeManager(ErrorModes errorMode)
 {
     _oldErrorMode = Unmanaged.SetErrorMode(errorMode);
 }
Exemple #24
0
        public static Win32Process StartProcessAsUser(WindowsIdentity winIdentity, string applicationName, string commandLine, string workingDirectory, Win32NativeEnvironmentBlock environment, out Stream stdin, out Stream stdout, out Stream stderror)
        {
            STARTUPINFO si = new STARTUPINFO();

            si.cb = Marshal.SizeOf(typeof(STARTUPINFO));

            /*
             * When a process is started using CreateProcessAsUser function, the process will be started into a windowstation
             * and desktop combination based on the value of lpDesktop in the STARTUPINFO structure parameter:
             * lpDesktop = "<windowsta>\<desktop>"; the system will try to start the process into that windowstation and desktop.
             * lpDesktop = NULL; the system will try to use the same windowstation and desktop as the calling process if the system is associated with the interactive windowstation.
             * lpDesktop = <somevalue>; the system will create a new windowstation and desktop that you cannot see.
             * lpDesktop = ""; it will either create a new windowstation and desktop that you cannot see, or if one has been created by means of a prior call by using the same access token, the existing windowstation and desktop will be used.
             */
            si.lpDesktop = "";

            IntPtr stdinRead, stdinWrite, stdoutRead, stdoutWrite, stderrorRead, stderrorWrite;

            SECURITY_ATTRIBUTES sa = default(SECURITY_ATTRIBUTES);

            sa.nLength = Marshal.SizeOf(sa);
            sa.lpSecurityDescriptor = IntPtr.Zero;
            sa.bInheritHandle       = true;

            if (!CreatePipe(out stdinRead, out stdinWrite, ref sa, 0))
            {
                throw new Win32Exception(Marshal.GetLastWin32Error());
            }

            if (!SetHandleInformation(stdinWrite, HANDLE_FLAGS.INHERIT, HANDLE_FLAGS.None))
            {
                throw new Win32Exception(Marshal.GetLastWin32Error());
            }

            if (!CreatePipe(out stdoutRead, out stdoutWrite, ref sa, 0))
            {
                throw new Win32Exception(Marshal.GetLastWin32Error());
            }

            if (!SetHandleInformation(stdoutRead, HANDLE_FLAGS.INHERIT, HANDLE_FLAGS.None))
            {
                throw new Win32Exception(Marshal.GetLastWin32Error());
            }

            if (!CreatePipe(out stderrorRead, out stderrorWrite, ref sa, 0))
            {
                throw new Win32Exception(Marshal.GetLastWin32Error());
            }

            if (!SetHandleInformation(stderrorRead, HANDLE_FLAGS.INHERIT, HANDLE_FLAGS.None))
            {
                throw new Win32Exception(Marshal.GetLastWin32Error());
            }

            si.dwFlags    = STARTF_USESTDHANDLES;
            si.hStdInput  = stdinRead;
            si.hStdOutput = stdoutWrite;
            si.hStdError  = stderrorWrite;

            SECURITY_ATTRIBUTES processAttr = CreateSecurityAttributes(winIdentity == null ? WellKnownSidType.AuthenticatedUserSid : WellKnownSidType.NetworkServiceSid);
            SECURITY_ATTRIBUTES threadAttr  = CreateSecurityAttributes(winIdentity == null ? WellKnownSidType.AuthenticatedUserSid : WellKnownSidType.NetworkServiceSid);

            lock (_createProcessLock) {
                PROCESS_INFORMATION pi;
                ErrorModes          oldErrorMode = SetErrorMode(ErrorModes.SEM_FAILCRITICALERRORS);
                try {
                    if (winIdentity == null)
                    {
                        if (!CreateProcess(applicationName, commandLine, ref processAttr, ref threadAttr, true,
                                           (uint)(CREATE_PROCESS_FLAGS.CREATE_UNICODE_ENVIRONMENT | CREATE_PROCESS_FLAGS.CREATE_NO_WINDOW),
                                           environment.NativeEnvironmentBlock,
                                           workingDirectory,
                                           ref si,
                                           out pi))
                        {
                            throw new Win32Exception(Marshal.GetLastWin32Error());
                        }
                    }
                    else
                    {
                        if (!CreateProcessAsUser(
                                winIdentity.Token, applicationName, commandLine, ref processAttr, ref threadAttr, true,
                                (uint)(CREATE_PROCESS_FLAGS.CREATE_UNICODE_ENVIRONMENT | CREATE_PROCESS_FLAGS.CREATE_NO_WINDOW),
                                environment.NativeEnvironmentBlock,
                                workingDirectory,
                                ref si,
                                out pi))
                        {
                            throw new Win32Exception(Marshal.GetLastWin32Error());
                        }
                    }

                    stdin    = new FileStream(new SafeFileHandle(stdinWrite, true), FileAccess.Write, 0x1000, false);
                    stdout   = new FileStream(new SafeFileHandle(stdoutRead, true), FileAccess.Read, 0x1000, false);
                    stderror = new FileStream(new SafeFileHandle(stderrorRead, true), FileAccess.Read, 0x1000, false);
                } finally {
                    SetErrorMode(oldErrorMode);

                    if (processAttr.lpSecurityDescriptor != IntPtr.Zero)
                    {
                        Marshal.FreeHGlobal(processAttr.lpSecurityDescriptor);
                    }

                    if (threadAttr.lpSecurityDescriptor != IntPtr.Zero)
                    {
                        Marshal.FreeHGlobal(threadAttr.lpSecurityDescriptor);
                    }
                }

                return(new Win32Process(pi));
            }
        }
Exemple #25
0
        public static IEnumerable <FileSystemInfo> GetFileSystemInfos(DirectoryInfo dir, string pattern, SearchOption searchOption, bool includeDirectories, bool includeFiles)
        {
            // We suppressed this demand for each p/invoke call, so demand it upfront once
            new SecurityPermission(SecurityPermissionFlag.UnmanagedCode).Demand();

            // Validate parameters
            if (dir == null)
            {
                throw new ArgumentNullException("dir");
            }
            if (pattern == null)
            {
                throw new ArgumentNullException("pattern");
            }

            // Setup
            WIN32_FIND_DATA       findData    = new WIN32_FIND_DATA();
            Stack <DirectoryInfo> directories = new Stack <DirectoryInfo>();

            directories.Push(dir);

            // Process each directory
            ErrorModes origErrorMode = SetErrorMode(ErrorModes.FailCriticalErrors);

            try
            {
                while (directories.Count > 0)
                {
                    // Get the name of the next directory and the corresponding search pattern
                    dir = directories.Pop();
                    string dirPath = dir.FullName.Trim();
                    if (dirPath.Length == 0)
                    {
                        continue;
                    }
                    char lastChar = dirPath[dirPath.Length - 1];
                    if (lastChar != Path.DirectorySeparatorChar && lastChar != Path.AltDirectorySeparatorChar)
                    {
                        dirPath += Path.DirectorySeparatorChar;
                    }

                    // Process all files in that directory
                    SafeFindHandle handle = FindFirstFile(dirPath + pattern, findData);
                    if (handle.IsInvalid)
                    {
                        int error = Marshal.GetLastWin32Error();
                        if (error == ERROR_ACCESS_DENIED ||
                            error == ERROR_FILE_NOT_FOUND)
                        {
                            continue;
                        }
                        else
                        {
                            throw new Win32Exception(error);
                        }
                    }
                    else
                    {
                        try
                        {
                            do
                            {
                                if ((findData.dwFileAttributes & FileAttributes.Directory) == 0)
                                {
                                    if (includeFiles)
                                    {
                                        yield return(new FileInfo(dirPath + findData.cFileName));
                                    }
                                }
                                else
                                {
                                    if (includeDirectories && findData.cFileName != "." && findData.cFileName != "..")
                                    {
                                        yield return(new DirectoryInfo(dirPath + findData.cFileName));
                                    }
                                }
                            }while (FindNextFile(handle, findData));
                            int error = Marshal.GetLastWin32Error();
                            if (error != ERROR_NO_MORE_FILES)
                            {
                                throw new Win32Exception(error);
                            }
                        }
                        finally { handle.Dispose(); }
                    }

                    // Add all child directories if that's what the user wants
                    if (searchOption == SearchOption.AllDirectories)
                    {
                        try
                        {
                            foreach (DirectoryInfo childDir in GetDirectories(dir, "*", SearchOption.TopDirectoryOnly))                             //Top only, as we're all ready handling recursion here.
                            {
                                try
                                {
                                    if ((File.GetAttributes(childDir.FullName) & FileAttributes.ReparsePoint) == 0)
                                    {
                                        directories.Push(childDir);
                                    }
                                }
                                catch (Exception childDirEx)
                                {
                                    //Can't get subfolders
                                    System.Diagnostics.Trace.WriteLine("Can't search inside: " + childDir.Name);
                                    System.Diagnostics.Trace.Indent();
                                    System.Diagnostics.Trace.WriteLine(childDirEx.Message);
                                    System.Diagnostics.Trace.Unindent();
                                }
                            }
                        }
                        catch (Exception e)
                        {
                            //Can't get subfolders
                            System.Diagnostics.Trace.WriteLine("Can't search inside: " + dirPath);
                            System.Diagnostics.Trace.Indent();
                            System.Diagnostics.Trace.WriteLine(e.Message);
                            System.Diagnostics.Trace.Unindent();
                        }
                    }
                }
            }
            finally { SetErrorMode(origErrorMode); }
        }
Exemple #26
0
 public ChangeErrorMode(ErrorModes mode)
 {
     oldMode = SetErrorMode((int)mode);
 }
Exemple #27
0
 internal static extern ErrorModes SetErrorMode(ErrorModes mode);
 static extern ErrorModes SetErrorMode(ErrorModes uMode);
Exemple #29
0
        public static IEnumerable <FileInfo> GetFiles(DirectoryInfo startDirectory, string pattern, bool recurse)
        {
            // We suppressed this demand for each p/invoke call, so demand it upfront once
            new SecurityPermission(SecurityPermissionFlag.UnmanagedCode).Demand();

            // Validate parameters
            Verify.IsNotNull(startDirectory, "startDirectory");
            Verify.IsNeitherNullNorEmpty(pattern, "pattern");

            // Setup
            var findData    = new WIN32_FIND_DATAW();
            var directories = new Stack <DirectoryInfo>();

            directories.Push(startDirectory);

            // Process each directory.  Only push new directories if we're recursing.
            ErrorModes origErrorMode = NativeMethods.SetErrorMode(ErrorModes.FailCriticalErrors);

            try
            {
                while (directories.Count > 0)
                {
                    // Get the name of the next directory and the corresponding search pattern
                    DirectoryInfo dir     = directories.Pop();
                    string        dirPath = dir.FullName.Trim();
                    if (dirPath.Length == 0)
                    {
                        continue;
                    }
                    char lastChar = dirPath[dirPath.Length - 1];
                    if (lastChar != Path.DirectorySeparatorChar && lastChar != Path.AltDirectorySeparatorChar)
                    {
                        dirPath += Path.DirectorySeparatorChar;
                    }

                    // Process all files in that directory
                    using (SafeFindHandle handle = NativeMethods.FindFirstFileW(dirPath + pattern, findData))
                    {
                        Win32Error error;
                        if (handle.IsInvalid)
                        {
                            error = Win32Error.GetLastError();
                            if (error == Win32Error.ERROR_ACCESS_DENIED || error == Win32Error.ERROR_FILE_NOT_FOUND)
                            {
                                continue;
                            }
                            Assert.AreNotEqual(Win32Error.ERROR_SUCCESS, error);
                            ((HRESULT)error).ThrowIfFailed();
                        }

                        do
                        {
                            if (!Utility.IsFlagSet((int)findData.dwFileAttributes, (int)FileAttributes.Directory))
                            {
                                yield return(new FileInfo(dirPath + findData.cFileName));
                            }
                        }while (NativeMethods.FindNextFileW(handle, findData));
                        error = Win32Error.GetLastError();
                        if (error != Win32Error.ERROR_NO_MORE_FILES)
                        {
                            ((HRESULT)error).ThrowIfFailed();
                        }
                    }

                    // Push subdirectories onto the stack if we are recursing.
                    if (recurse)
                    {
                        // In a volatile system we can't count on all the file information staying valid.
                        // Catch reasonable exceptions and move on.
                        try
                        {
                            foreach (DirectoryInfo childDir in dir.GetDirectories())
                            {
                                try
                                {
                                    FileAttributes attrib = File.GetAttributes(childDir.FullName);
                                    // If it's not a hidden, system folder, nor a reparse point
                                    if (!Utility.IsFlagSet((int)attrib, (int)(FileAttributes.Hidden | FileAttributes.System | FileAttributes.ReparsePoint)))
                                    {
                                        directories.Push(childDir);
                                    }
                                }
                                catch (FileNotFoundException)
                                {
                                    // Shouldn't see this.
                                    Assert.Fail();
                                }
                                catch (DirectoryNotFoundException) { }
                            }
                        }
                        catch (DirectoryNotFoundException) { }
                    }
                }
            }
            finally
            {
                NativeMethods.SetErrorMode(origErrorMode);
            }
        }
Exemple #30
0
 [DllImport("kernel32.dll", SetLastError = true)] static extern ErrorModes SetErrorMode(ErrorModes uMode);
Exemple #31
0
 [DllImport("kernel32.dll")] public static extern ErrorModes SetErrorMode(ErrorModes uMode);
Exemple #32
0
 public ChangeErrorMode(ErrorModes mode)
 {
     Environment.ExitCode = oldMode = (int)mode;
 }
Exemple #33
0
 internal static extern ErrorModes SetErrorMode(ErrorModes mode);
Exemple #34
0
 public void SetErrorMode_Works()
 {
     ErrorModes oldMode = SetErrorMode(ErrorModes.SEM_DEFAULT);
 }
Exemple #35
0
 static extern ErrorModes SetErrorMode(ErrorModes uMode);
Exemple #36
0
        /// <summary>
        /// Gets the files.
        /// </summary>
        /// <param name="dir">The dir.</param>
        /// <param name="pattern">The pattern.</param>
        /// <param name="searchOption">The search option.</param>
        /// <returns></returns>
        public static IEnumerable <FileInfo> GetFiles(DirectoryInfo dir, string pattern, SearchOption searchOption)
        {
            // We suppressed this demand for each p/invoke call, so demand it upfront once
            new SecurityPermission(SecurityPermissionFlag.UnmanagedCode).Demand();

            // Validate parameters
            if (dir == null)
            {
                throw new ArgumentNullException("dir");
            }
            if (pattern == null)
            {
                throw new ArgumentNullException("pattern");
            }

            // Setup
            WIN32_FIND_DATA       findData    = new WIN32_FIND_DATA();
            Stack <DirectoryInfo> directories = new Stack <DirectoryInfo>();

            directories.Push(dir);

            // Process each directory
            ErrorModes origErrorMode = SetErrorMode(ErrorModes.FailCriticalErrors);

            try
            {
                while (directories.Count > 0)
                {
                    // Get the name of the next directory and the corresponding search pattern
                    dir = directories.Pop();
                    string dirPath = dir.FullName.Trim();
                    if (dirPath.Length == 0)
                    {
                        continue;
                    }
                    char lastChar = dirPath[dirPath.Length - 1];
                    if (lastChar != Path.DirectorySeparatorChar && lastChar != Path.AltDirectorySeparatorChar)
                    {
                        dirPath += Path.DirectorySeparatorChar;
                    }

                    // Process all files in that directory
                    SafeFindHandle handle = FindFirstFile(dirPath + pattern, findData);
                    if (handle.IsInvalid)
                    {
                        int error = Marshal.GetLastWin32Error();
                        if (error == ERROR_ACCESS_DENIED)
                        {
                            continue;
                        }
                        else if (error != ERROR_FILE_NOT_FOUND)
                        {
                            throw new Win32Exception(error);
                        }
                    }
                    else
                    {
                        try
                        {
                            do
                            {
                                if ((findData.dwFileAttributes & FileAttributes.Directory) == 0)
                                {
                                    yield return(new FileInfo(dirPath + findData.cFileName));
                                }
                            }while (FindNextFile(handle, findData));
                            int error = Marshal.GetLastWin32Error();
                            if (error != ERROR_NO_MORE_FILES)
                            {
                                throw new Win32Exception(error);
                            }
                        }
                        finally { handle.Dispose(); }
                    }

                    // Add all child directories if that's what the user wants
                    if (searchOption == SearchOption.AllDirectories)
                    {
                        foreach (DirectoryInfo childDir in dir.GetDirectories())
                        {
                            if ((File.GetAttributes(childDir.FullName) & FileAttributes.ReparsePoint) == 0)
                            {
                                directories.Push(childDir);
                            }
                        }
                    }
                }
            }
            finally { SetErrorMode(origErrorMode); }
        }
 public static extern ErrorModes SetErrorMode(ErrorModes newMode);
 public ChangeErrorMode(ErrorModes mode)
 {
     try
     {
         oldMode = SetErrorMode((int)mode);
     }
     catch (EntryPointNotFoundException)
     {
         oldMode = (int)mode;
     }
 }