打开filedialog来查找文件名的路径和扩展名

本文关键字:路径 扩展名 文件名 filedialog 查找 打开 | 更新日期: 2023-09-27 18:09:05

我试图在c#中使用user32kernal32找到文件扩展名,路径和文件大小。

我的场景:在网上上传一些文件(电子邮件,应用程序等)我需要获取文件名,它的路径和文件的大小(文件的大小是可选的)。我使用OpenFileDialog处理,我可以检索要上传的选定文件的文件名。你可以帮我检索路径和大小的文件使用相同。我可以找到OpenFileDialog的句柄,如何使用这些句柄

继续检索信息

请找到我下面的代码(一些DLL参考将不有用):

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Runtime.InteropServices;
using System.IO;
using System.Security.Principal;
using `enter code here`System.Diagnostics;
namespace Opendailoghandle
{
    class Program
    {
        [DllImport("user32.dll")]
        static extern IntPtr FindWindow(string lpClassName, string lpWindowName);
        [DllImport("user32.dll")]
        static extern IntPtr FindWindowEx(IntPtr hwndParent, IntPtr hwndChildAfter, string lpszClass, string lpszWindow);
        [DllImport("user32.dll", CharSet = CharSet.Auto)]
        static extern IntPtr SendMessage(HandleRef hWnd, uint Msg, int wParam, StringBuilder lParam);
        //  [DllImport("user32.dll", CharSet = CharSet.Auto)]
        //  public static extern int SendMessage(int hWnd, int msg, int wParam, IntPtr lParam);
        [DllImport("user32.dll", CharSet = CharSet.Auto)]
        public static extern IntPtr GetDlgItem(IntPtr hwnd, int childID);
        [DllImport("user32.dll", CharSet = CharSet.Auto)]
        static extern int SendMessage(HandleRef hwnd, int wMsg, int wParam, String s);
        [DllImport("user32.dll", CharSet = CharSet.Auto)]
        static extern String SendMessage(HandleRef hwnd, uint WM_GETTEXT);
        [DllImport("user32.dll", CharSet = CharSet.Auto)]
        public static extern int SendMessage(int hWnd, int msg, int wParam, IntPtr lParam);
        // to get file size import
        [DllImport("kernel32.dll")]
        static extern bool GetFileSizeEx(IntPtr hFile, out long lpFileSize);
        [DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
        public static extern IntPtr CreateFile(
     [MarshalAs(UnmanagedType.LPTStr)] string filename,
     [MarshalAs(UnmanagedType.U4)] FileAccess access,
     [MarshalAs(UnmanagedType.U4)] FileShare share,
     IntPtr securityAttributes, // optional SECURITY_ATTRIBUTES struct or IntPtr.Zero
     [MarshalAs(UnmanagedType.U4)] FileMode creationDisposition,
     [MarshalAs(UnmanagedType.U4)] FileAttributes flagsAndAttributes,
     IntPtr templateFile);
        [DllImport("kernel32.dll", SetLastError = true)]
        [return: MarshalAs(UnmanagedType.Bool)]
        static extern bool CloseHandle(IntPtr hObject);
        [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
        public struct  WIN32_FIND_DATA
        {
            public int dwFileAttributes;
            public FILETIME ftCreationTime;
            public FILETIME ftLastAccessTime;
            public FILETIME ftLastWriteTime;
            public int nFileSizeHigh;
            public int nFileSizeLow;
            public int dwReserved0;
            public int dwReserved1;
            public string cFileName; //mite need marshalling, TCHAR size = MAX_PATH???
            public string cAlternateFileName; //mite need marshalling, TCHAR size = 14
        }
        public struct WIN32_FIND_DATA1
        {
            public int dwFileAttributes;
            public System.Runtime.InteropServices.ComTypes.FILETIME ftCreationTime;
            public System.Runtime.InteropServices.ComTypes.FILETIME ftLastAccessTime;
            public System.Runtime.InteropServices.ComTypes.FILETIME ftLastWriteTime;
            public int nFileSizeHigh;
            public int nFileSizeLow;
            public int dwReserved0;
            public int dwReserved1;
            [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 260)]
            public string cFileName;
            [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 14)]
            public string cAlternateFileName;
        }
        [DllImport("kernel32.dll", CharSet = CharSet.Auto)]
        static extern IntPtr FindFirstFile(string lpFileName, out WIN32_FIND_DATA lpFindFileData);
        [DllImport("kernel32.dll")]
        static extern IntPtr FindFirstFile(IntPtr lpfilename, ref WIN32_FIND_DATA findfiledata);
        [DllImport("kernel32.dll")]
        static extern IntPtr FindClose(IntPtr pff);

        [DllImport("User32.dll")]
        public static extern bool SetForegroundWindow(IntPtr hWnd);
        public static Process[] myProcess = Process.GetProcessesByName("program name here");

        const uint WM_GETTEXT = 0x0D;
        const uint WM_GETTEXTLENGTH = 0X0E;
        const int BN_CLICKED = 245;
        private const int WM_SETTEXT = 0x000C;
        static void Main()
        {
            IntPtr hWnd = FindWindow(null, "Open");
            if (hWnd != IntPtr.Zero)
            {
                Console.WriteLine("Open File Dialog is open");

                IntPtr hwndButton = FindWindowEx(hWnd, IntPtr.Zero, "Button", "&Open");
                Console.WriteLine("The handle of the Open button is " + hwndButton);
                IntPtr FileDialogHandle = FindWindow(null, "Open");
                IntPtr iptrHWndControl = GetDlgItem(FileDialogHandle, 1148);
                HandleRef hrefHWndTarget = new HandleRef(null, iptrHWndControl);
                //SendMessage(hrefHWndTarget, WM_SETTEXT, 0, "your file path");
                IntPtr opnButton = FindWindowEx(FileDialogHandle, IntPtr.Zero, "Open", null);
                SendMessage((int)opnButton, BN_CLICKED, 0, IntPtr.Zero);
                int len = (int)SendMessage(hrefHWndTarget, WM_GETTEXTLENGTH, 0, null);
                var sb = new StringBuilder(len + 1);
                SendMessage(hrefHWndTarget, WM_GETTEXT, sb.Capacity, sb);
                string text = sb.ToString();
                //FileInfo f = new FileInfo(text);
                DirectoryInfo hdDirectoryInWhichToSearch = new DirectoryInfo(@"c:'");
                FileInfo[] filesInDir = hdDirectoryInWhichToSearch.GetFiles("*" + text + "*.*");
                foreach (FileInfo foundFile in filesInDir)
                {
                    string fullName = foundFile.FullName;
                    Console.WriteLine(fullName);
                }
                var newName = DateTime.Now;
                var Username = (WindowsIdentity.GetCurrent().Name);
                //var contentArray = GetFileSizeB(text);

                Console.WriteLine("The Edit box contains " + text+"'tsize:"+contentArray + "'nUser Name "+Username +"'tTime : "+newName );
            }
            else
            {
                Console.WriteLine("Open File Dialog is not open");
            }
            Console.ReadKey();
        }
        //public static uint GetFileSizeB(string filename)
        //{
        //    IntPtr handle = CreateFile(
        //        filename,
        //        FileAccess.Read,
        //        FileShare.Read,
        //        IntPtr.Zero,
        //        FileMode.Open,
        //        FileAttributes.ReadOnly,
        //        IntPtr.Zero);
        //    if (handle.ToInt32() == -1)
        //    {
        //        return 1;
        //    }
        //    long fileSize;
        //    GetFileSizeEx(handle, out fileSize);
        //    CloseHandle(handle);
        //    return (uint)fileSize;
        //}
    }
}*

打开filedialog来查找文件名的路径和扩展名

检查您的FileInfo类,它包含属性,如长度,路径,扩展…

通过filesInDir…

文件循环的例子

你可以得到文件名,路径,长度等,像下面

int LengthInBytes = foundFile.Length;

Hope This help…

string path = "C:''Test";
DirectoryInfo di = new DirectoryInfo(path);
FileInfo[] filesInDir = di.GetFiles();
foreach (FileInfo foundFile in filesInDir)
{
  string fullName = foundFile.FullName;
  long fileLength = foundFile.Length;
  string fileName = foundFile.Name;
  string extension = foundFile.Extension;
  /// etc
  Console.WriteLine(fullName);
}

使用OpenFileDialog

OpenFileDialog ofd = new OpenFileDialog();
if (ofd.ShowDialog() == DialogResult.OK)
{
    string fileName = ofd.FileName;
    MessageBox.Show("FName: " + fileName);
}

这将是文件的完整路径的字符串。如果你在OpenDialogBox上设置了MultiSelect,它将返回一个完整文件名的字符串数组。

按OP进一步规范编辑

您可以使用System.IO.FileInfo类获取文件信息。下面是示例代码。

private static void ShowFileDetails()
{
    List<string> lstFiles = System.IO.Directory.GetFiles(@"D:'downloads").ToList(); //Need to pass the folder path to get the files.
    foreach (string file in lstFiles)
    {
        System.IO.FileInfo fi = new System.IO.FileInfo(file);
        Console.WriteLine(string.Format("Extension={0}'tFile Name={1}'tFile Size={2} bytes'tFile Path={3}'tCreated On={4}'tModified On={5}",
                            fi.Extension,
                            fi.Name,
                            fi.Length,
                            fi.FullName,
                            fi.CreationTime,
                            fi.LastWriteTime));
    }
    Console.ReadLine();
}