C#:OpenFileDialog查找文件名的路径和扩展名

时间:2016-09-28 06:57:22

标签: c# .net filepath user32 kernel32

我正在尝试使用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;

        //}

    }
}*

2 个答案:

答案 0 :(得分:1)

检查您的FileInfo类,其中包含长度,路径,扩展名等属性。

循环浏览filesInDir中的文件的示例...

您可以获取fileName,Path,Length等,如下所示

int LengthInBytes = foundFile.Length;

希望这有助于......

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,它将返回一个完整文件名的字符串数组。

答案 1 :(得分:0)

按照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();
}