C#:OpenFileDialog查找文件名的路径和超限值

问题描述:

我正在试图在c#中使用user32kernal32来查找文件扩展名,路径和文件大小。我需要获取文件名,文件路径和文件大小(文件大小是可选的)。我需要获取文件名,文件路径和大小(文件大小是可选的)。我正在使用OpenFileDialog句柄,我可以检索所选文件的上传文件名。你能帮我找回文件的路径和大小吗?我能找到手感的OpenFileDialog如何继续使用这些处理C#: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; 

     //} 

    } 
}* 

检查FileInfo类它包含了像长度,路径,扩展性能。在通过filesInDir文件的循环

例...

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

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

+0

谢谢Balagurunathan对你有帮助的编辑。 – JohnG

+0

不客气! –

+0

感谢您的回复我试过fileinfo,但我只能得到文件名的清单,如输出:打开文件对话框打开 打开按钮的句柄是1377394 编辑框包含DialyUpdates_shayidha_090816 DIR:c:\ users \ 732468 \ documents \ visual studio 2015 \ Projects \ Opendailoghandle \ Opendailoghandle \ bin \ Debug但实际路径是从C:\ Documents.how获取实际路径?和大小 –

编辑为每个操作的进一步规范

可以抽到使用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(); 
} 
+0

感谢您的回复。我忘了提及我正在使用C#控制台应用程序开发。这段代码将无法以“OpenfileDialog”(使用system.windows.form)获取我所需的详细信息。如果我错了,请指导我使用此 –

+0

的扩展结果我可以知道,从哪里获取文件名?你的文件名是否像'C:\ Users \ User1 \ test.txt'? –

+0

我试图从“C:\”目录中获取文件信息的代码,它对那个特定目录(但不适用于内部文件夹)正常工作。假设如果我从“D:\”中选择文件,代码将不会应用到它,但我需要使用独立于目录的文件名来查找文件路径。我试图从例如上传文件。 D:\ downloads \ JAL.doc @ balagurunathan-marimuthu –