Hack Forums
[C#] [Snippet] Get Windows directory - Printable Version

+- Hack Forums (https://hackforums.net)
+-- Forum: Tech (https://hackforums.net/forumdisplay.php?fid=444)
+--- Forum: Coding (https://hackforums.net/forumdisplay.php?fid=151)
+---- Forum: Software Development (https://hackforums.net/forumdisplay.php?fid=118)
+---- Thread: [C#] [Snippet] Get Windows directory (/showthread.php?tid=5914167)



[Snippet] Get Windows directory - gigajew - Dec 1, 2018

Here's a snippet to get the Windows directory using the Windows API. Easy to use.

Code
[DllImport("kernel32.dll", BestFitMapping = true, CallingConvention = CallingConvention.Winapi, CharSet = CharSet.Unicode, SetLastError = true)]
        [return: MarshalAs(UnmanagedType.U4)]
        private static extern uint GetWindowsDirectory(StringBuilder builder, [MarshalAs(UnmanagedType.U4)] uint size);

        private static DirectoryInfo GetWindowsDirectory()
        {
            StringBuilder builder = new StringBuilder(260);
            uint realLength = GetWindowsDirectory( builder, (uint)builder.Capacity);
            string windowsDir = builder.ToString();
            return new DirectoryInfo(windowsDir);
        }



RE: [Snippet] Get Windows directory - Vuln - Dec 1, 2018

Why use WinAPI for this at all?

Code
new DirectoryInfo(Environment.GetFolderPath(Environment.SpecialFolder.Windows));



RE: [Snippet] Get Windows directory - 0xDEAD10CC - Dec 1, 2018

(Dec 1, 2018 08:35 AM)Jailbyte Wrote:  Why use WinAPI for this at all?

Code
new DirectoryInfo(Environment.GetFolderPath(Environment.SpecialFolder.Windows));

^ Exactly

Additionally if you actually read the documentation it says size should be MAX_PATH, and that is not 255... It's 260.


RE: [Snippet] Get Windows directory - gigajew - Dec 1, 2018

Thanks for the input, changed accordingly