473,473 Members | 1,807 Online
Bytes | Software Development & Data Engineering Community
Create Post

Home Posts Topics Members FAQ

How to Detect the Currently Opened Files in VB.net for Media Centre

5 New Member
Hi Guys,

I am writing a Media Centre Addin in Vb.net and it was all going good until i got to the point where i want to find the "Currently Playing song FilePath or URl"

I have spend a number of hours racking my brain to figure out a way of seeing what the "Currently Opened Files" are on a machine at any point of time.

My idea is to get all the currently opened files, and then filter the Extensions from these and find the media item that is currently playing, and get the filepath..

Does anyone know how i can do this? and what methods or classes or Librarys i should be looking at or importing In.. This one has really got me thinking.

I was looking at the WMI Windows Management controls, but cant seem to find what i am looking for.. any help would be great..

Cheers

Robbie
Apr 8 '09 #1
10 5062
robbietapping
5 New Member
Hi Guys,
Worked this one out, will post a reply in the next few days if anyone wants to know how to do it.

Cheers

Robbie
Apr 13 '09 #2
Frinavale
9,735 Recognized Expert Moderator Expert
Sharing the solution is a great idea so that others facing the same problem will be able to find the answer....otherwise you're just going to leave them hanging.

If you could share your solution it would be greatly appreciated.

Thanks

-Frinny
Apr 14 '09 #3
robbietapping
5 New Member
Hi Guys,

Thought i would send through the Vb.net code for how to get the currently playing song in a Media Centre Environment.

The way it works is it hooks on to the backgroup WMPlayer process, and sees what files it currently has opened, it then loops throught them until it finds a matching extention.

This code will also work in a standard application without media centre..
Expand|Select|Wrap|Line Numbers
  1.     Public Function GetCurrentlyPlayingMediaName() As String
  2.         Try
  3.  
  4.             Dim pid As Integer = 0
  5.             Dim filename As String = Nothing
  6.             Dim mysession As Integer = 0
  7.             ' Get the session ID for the current process 
  8.             Using currentProcess As Process = Process.GetCurrentProcess()
  9.                 mysession = currentProcess.SessionId
  10.             End Using
  11.  
  12.             ' Find the matching ehshell process in the same session 
  13.             For Each proc As Process In Process.GetProcessesByName("wmplayer")
  14.                 If proc.SessionId = mysession Then
  15.                     pid = proc.Id
  16.                 End If
  17.                 proc.Dispose()
  18.             Next
  19.  
  20.             ' Check we found a process, if not, abort 
  21.             If pid = 0 Then
  22.                 Trace.TraceWarning("No wmplaye process found")
  23.                 Return Nothing
  24.             End If
  25.  
  26.             ' Get the list of open files by the ehshell process 
  27.             Using openFiles As IEnumerator(Of FileSystemInfo) = DetectOpenFiles.GetOpenFilesEnumerator(pid)
  28.                 ' Iterate until we find a .dvr-ms file 
  29.                 While openFiles.MoveNext()
  30.                     If openFiles.Current.Extension.ToLower(CultureInfo.InvariantCulture) = ".mp3" Then
  31.                         filename = openFiles.Current.FullName
  32.                         Exit While
  33.                     End If
  34.                     If openFiles.Current.Extension.ToLower(CultureInfo.InvariantCulture) = ".mp4" Then
  35.                         filename = openFiles.Current.FullName
  36.                         Exit While
  37.                     End If
  38.                     If openFiles.Current.Extension.ToLower(CultureInfo.InvariantCulture) = ".m4a" Then
  39.                         filename = openFiles.Current.FullName
  40.                         Exit While
  41.                     End If
  42.                     If openFiles.Current.Extension.ToLower(CultureInfo.InvariantCulture) = ".wma" Then
  43.                         filename = openFiles.Current.FullName
  44.                         Exit While
  45.                     End If
  46.                 End While
  47.             End Using
  48.  
  49.             Return filename
  50.  
  51.         Catch ex As Exception
  52.             Log.Write("Unable to get Currently Playing Media: " & ex.Message)
  53.             Return Nothing
  54.         End Try
  55.  
  56.     End Function
Hope this helps someone out there

Cheers

Robbie
Apr 15 '09 #4
Frinavale
9,735 Recognized Expert Moderator Expert
Thanks a lot Robbie :)
Your response is nicely detailed!
Apr 15 '09 #5
waco78
1 New Member
The DetectOpenFiles class seems to be missing? Where can I find this?


Thanks.
Apr 30 '09 #6
robbietapping
5 New Member
Hey Waco78, Apologies i forgot to add this code in here..

Johnathan Bradshaw (ABSOLUTE LEGEND) wrote this class to go and re-iterate through the process nodes and see what is being opened.

The way i did it was (Cause its in C#) instead of just converting the code.. i created a solution, and compiled the c# code as a library file, then was able to reference it in the C#. net, obviously there are easy ways, but the way my application has been set-up code wise, this was the easiest option.

if you have any problems let me know.... it should not be too fiddly or complicated at all.


Here is the C# Code:
Expand|Select|Wrap|Line Numbers
  1. using System;
  2. using System.Collections.Generic;
  3. using System.EnterpriseServices;
  4. using System.IO;
  5. using System.Runtime.CompilerServices;
  6. using System.Runtime.ConstrainedExecution;
  7. using System.Runtime.InteropServices;
  8. using System.Security.Permissions;
  9. using System.Text;
  10. using System.Threading;
  11. using Microsoft.Win32.SafeHandles;
  12.  
  13. namespace VmcController.Services
  14. {
  15.     #region ENUMs
  16.     internal enum NT_STATUS
  17.     {
  18.         STATUS_SUCCESS = 0x00000000,
  19.         STATUS_BUFFER_OVERFLOW = unchecked((int)0x80000005L),
  20.         STATUS_INFO_LENGTH_MISMATCH = unchecked((int)0xC0000004L)
  21.     }
  22.  
  23.     internal enum SYSTEM_INFORMATION_CLASS
  24.     {
  25.         SystemBasicInformation = 0,
  26.         SystemPerformanceInformation = 2,
  27.         SystemTimeOfDayInformation = 3,
  28.         SystemProcessInformation = 5,
  29.         SystemProcessorPerformanceInformation = 8,
  30.         SystemHandleInformation = 16,
  31.         SystemInterruptInformation = 23,
  32.         SystemExceptionInformation = 33,
  33.         SystemRegistryQuotaInformation = 37,
  34.         SystemLookasideInformation = 45
  35.     }
  36.  
  37.     internal enum OBJECT_INFORMATION_CLASS
  38.     {
  39.         ObjectBasicInformation = 0,
  40.         ObjectNameInformation = 1,
  41.         ObjectTypeInformation = 2,
  42.         ObjectAllTypesInformation = 3,
  43.         ObjectHandleInformation = 4
  44.     }
  45.  
  46.     [Flags]
  47.     internal enum ProcessAccessRights
  48.     {
  49.         PROCESS_DUP_HANDLE = 0x00000040
  50.     }
  51.  
  52.     [Flags]
  53.     internal enum DuplicateHandleOptions
  54.     {
  55.         DUPLICATE_CLOSE_SOURCE = 0x1,
  56.         DUPLICATE_SAME_ACCESS = 0x2
  57.     }
  58.     #endregion
  59.  
  60.     [SecurityPermission(SecurityAction.LinkDemand, UnmanagedCode = true)]
  61.     internal sealed class SafeObjectHandle : SafeHandleZeroOrMinusOneIsInvalid
  62.     {
  63.         private SafeObjectHandle()
  64.             : base(true)
  65.         { }
  66.  
  67.         internal SafeObjectHandle(IntPtr preexistingHandle, bool ownsHandle)
  68.             : base(ownsHandle)
  69.         {
  70.             base.SetHandle(preexistingHandle);
  71.         }
  72.  
  73.         protected override bool ReleaseHandle()
  74.         {
  75.             return NativeMethods.CloseHandle(base.handle);
  76.         }
  77.     }
  78.  
  79.     [SecurityPermission(SecurityAction.LinkDemand, UnmanagedCode = true)]
  80.     internal sealed class SafeProcessHandle : SafeHandleZeroOrMinusOneIsInvalid
  81.     {
  82.         private SafeProcessHandle()
  83.             : base(true)
  84.         { }
  85.  
  86.         internal SafeProcessHandle(IntPtr preexistingHandle, bool ownsHandle)
  87.             : base(ownsHandle)
  88.         {
  89.             base.SetHandle(preexistingHandle);
  90.         }
  91.  
  92.         protected override bool ReleaseHandle()
  93.         {
  94.             return NativeMethods.CloseHandle(base.handle);
  95.         }
  96.     }
  97.  
  98.     #region Native Methods
  99.     internal static class NativeMethods
  100.     {
  101.         [DllImport("ntdll.dll")]
  102.         internal static extern NT_STATUS NtQuerySystemInformation(
  103.             [In] SYSTEM_INFORMATION_CLASS SystemInformationClass,
  104.             [In] IntPtr SystemInformation,
  105.             [In] int SystemInformationLength,
  106.             [Out] out int ReturnLength);
  107.  
  108.         [DllImport("ntdll.dll")]
  109.         internal static extern NT_STATUS NtQueryObject(
  110.             [In] IntPtr Handle,
  111.             [In] OBJECT_INFORMATION_CLASS ObjectInformationClass,
  112.             [In] IntPtr ObjectInformation,
  113.             [In] int ObjectInformationLength,
  114.             [Out] out int ReturnLength);
  115.  
  116.         [DllImport("kernel32.dll", SetLastError = true)]
  117.         internal static extern SafeProcessHandle OpenProcess(
  118.             [In] ProcessAccessRights dwDesiredAccess,
  119.             [In, MarshalAs(UnmanagedType.Bool)] bool bInheritHandle,
  120.             [In] int dwProcessId);
  121.  
  122.         [DllImport("kernel32.dll", SetLastError = true)]
  123.         [return: MarshalAs(UnmanagedType.Bool)]
  124.         internal static extern bool DuplicateHandle(
  125.             [In] IntPtr hSourceProcessHandle,
  126.             [In] IntPtr hSourceHandle,
  127.             [In] IntPtr hTargetProcessHandle,
  128.             [Out] out SafeObjectHandle lpTargetHandle,
  129.             [In] int dwDesiredAccess,
  130.             [In, MarshalAs(UnmanagedType.Bool)] bool bInheritHandle,
  131.             [In] DuplicateHandleOptions dwOptions);
  132.  
  133.         [DllImport("kernel32.dll")]
  134.         internal static extern IntPtr GetCurrentProcess();
  135.  
  136.         [DllImport("kernel32.dll", SetLastError = true)]
  137.         internal static extern int GetProcessId(
  138.             [In] IntPtr Process);
  139.  
  140.         [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
  141.         [DllImport("kernel32.dll", SetLastError = true)]
  142.         [return: MarshalAs(UnmanagedType.Bool)]
  143.         internal static extern bool CloseHandle(
  144.             [In] IntPtr hObject);
  145.  
  146.         [DllImport("kernel32.dll", SetLastError = true)]
  147.         internal static extern int QueryDosDevice(
  148.             [In] string lpDeviceName,
  149.             [Out] StringBuilder lpTargetPath,
  150.             [In] int ucchMax);
  151.     }
  152.     #endregion
  153.  
  154.     [ComVisible(true), EventTrackingEnabled(true)]
  155.     public class DetectOpenFiles : ServicedComponent
  156.     {
  157.         private static Dictionary<string, string> deviceMap;
  158.         private const string networkDevicePrefix = "\\Device\\LanmanRedirector\\";
  159.  
  160.         private const int MAX_PATH = 260;
  161.  
  162.         private enum SystemHandleType
  163.         {
  164.             OB_TYPE_UNKNOWN = 0,
  165.             OB_TYPE_TYPE = 1,
  166.             OB_TYPE_DIRECTORY,
  167.             OB_TYPE_SYMBOLIC_LINK,
  168.             OB_TYPE_TOKEN,
  169.             OB_TYPE_PROCESS,
  170.             OB_TYPE_THREAD,
  171.             OB_TYPE_UNKNOWN_7,
  172.             OB_TYPE_EVENT,
  173.             OB_TYPE_EVENT_PAIR,
  174.             OB_TYPE_MUTANT,
  175.             OB_TYPE_UNKNOWN_11,
  176.             OB_TYPE_SEMAPHORE,
  177.             OB_TYPE_TIMER,
  178.             OB_TYPE_PROFILE,
  179.             OB_TYPE_WINDOW_STATION,
  180.             OB_TYPE_DESKTOP,
  181.             OB_TYPE_SECTION,
  182.             OB_TYPE_KEY,
  183.             OB_TYPE_PORT,
  184.             OB_TYPE_WAITABLE_PORT,
  185.             OB_TYPE_UNKNOWN_21,
  186.             OB_TYPE_UNKNOWN_22,
  187.             OB_TYPE_UNKNOWN_23,
  188.             OB_TYPE_UNKNOWN_24,
  189.             //OB_TYPE_CONTROLLER,
  190.             //OB_TYPE_DEVICE,
  191.             //OB_TYPE_DRIVER,
  192.             OB_TYPE_IO_COMPLETION,
  193.             OB_TYPE_FILE
  194.         };
  195.  
  196.         private const int handleTypeTokenCount = 27;
  197.         private static readonly string[] handleTypeTokens = new string[] { 
  198.                 "", "", "Directory", "SymbolicLink", "Token",
  199.                 "Process", "Thread", "Unknown7", "Event", "EventPair", "Mutant",
  200.                 "Unknown11", "Semaphore", "Timer", "Profile", "WindowStation",
  201.                 "Desktop", "Section", "Key", "Port", "WaitablePort",
  202.                 "Unknown21", "Unknown22", "Unknown23", "Unknown24", 
  203.                 "IoCompletion", "File"
  204.             };
  205.  
  206.         [StructLayout(LayoutKind.Sequential)]
  207.         private struct SYSTEM_HANDLE_ENTRY
  208.         {
  209.             public int OwnerPid;
  210.             public byte ObjectType;
  211.             public byte HandleFlags;
  212.             public short HandleValue;
  213.             public int ObjectPointer;
  214.             public int AccessMask;
  215.         }
  216.  
  217.         /// <summary>
  218.         /// Gets the open files enumerator.
  219.         /// </summary>
  220.         /// <param name="processId">The process id.</param>
  221.         /// <returns></returns>
  222.         public static IEnumerator<FileSystemInfo> GetOpenFilesEnumerator(int processId)
  223.         {
  224.             return new OpenFiles(processId).GetEnumerator();
  225.         }
  226.  
  227.         private sealed class OpenFiles : IEnumerable<FileSystemInfo>
  228.         {
  229.             private readonly int processId;
  230.  
  231.             internal OpenFiles(int processId)
  232.             {
  233.                 this.processId = processId;
  234.             }
  235.  
  236.             #region IEnumerable<FileSystemInfo> Members
  237.  
  238.             public IEnumerator<FileSystemInfo> GetEnumerator()
  239.             {
  240.                 NT_STATUS ret;
  241.                 int length = 0x10000;
  242.                 // Loop, probing for required memory.
  243.  
  244.  
  245.                 do
  246.                 {
  247.                     IntPtr ptr = IntPtr.Zero;
  248.                     RuntimeHelpers.PrepareConstrainedRegions();
  249.                     try
  250.                     {
  251.                         RuntimeHelpers.PrepareConstrainedRegions();
  252.                         try { }
  253.                         finally
  254.                         {
  255.                             // CER guarantees that the address of the allocated 
  256.                             // memory is actually assigned to ptr if an 
  257.                             // asynchronous exception occurs.
  258.                             ptr = Marshal.AllocHGlobal(length);
  259.                         }
  260.                         int returnLength;
  261.                         ret = NativeMethods.NtQuerySystemInformation(SYSTEM_INFORMATION_CLASS.SystemHandleInformation, ptr, length, out returnLength);
  262.                         if (ret == NT_STATUS.STATUS_INFO_LENGTH_MISMATCH)
  263.                         {
  264.                             // Round required memory up to the nearest 64KB boundary.
  265.                             length = ((returnLength + 0xffff) & ~0xffff);
  266.                         }
  267.                         else if (ret == NT_STATUS.STATUS_SUCCESS)
  268.                         {
  269.                             int handleCount = Marshal.ReadInt32(ptr);
  270.                             int offset = sizeof(int);
  271.                             int size = Marshal.SizeOf(typeof(SYSTEM_HANDLE_ENTRY));
  272.                             for (int i = 0; i < handleCount; i++)
  273.                             {
  274.                                 SYSTEM_HANDLE_ENTRY handleEntry = (SYSTEM_HANDLE_ENTRY)Marshal.PtrToStructure((IntPtr)((int)ptr + offset), typeof(SYSTEM_HANDLE_ENTRY));
  275.                                 if (handleEntry.OwnerPid == processId)
  276.                                 {
  277.                                     IntPtr handle = (IntPtr)handleEntry.HandleValue;
  278.                                     SystemHandleType handleType;
  279.  
  280.                                     if (GetHandleType(handle, handleEntry.OwnerPid, out handleType) && handleType == SystemHandleType.OB_TYPE_FILE)
  281.                                     {
  282.                                         string devicePath;
  283.                                         if (GetFileNameFromHandle(handle, handleEntry.OwnerPid, out devicePath))
  284.                                         {
  285.                                             string dosPath;
  286.                                             if (ConvertDevicePathToDosPath(devicePath, out dosPath))
  287.                                             {
  288.                                                 if (File.Exists(dosPath))
  289.                                                 {
  290.                                                     yield return new FileInfo(dosPath);
  291.                                                 }
  292.                                                 else if (Directory.Exists(dosPath))
  293.                                                 {
  294.                                                     yield return new DirectoryInfo(dosPath);
  295.                                                 }
  296.                                             }
  297.                                         }
  298.                                     }
  299.                                 }
  300.                                 offset += size;
  301.                             }
  302.                         }
  303.                     }
  304.                     finally
  305.                     {
  306.                         // CER guarantees that the allocated memory is freed, 
  307.                         // if an asynchronous exception occurs. 
  308.                         Marshal.FreeHGlobal(ptr);
  309.                         //sw.Flush();
  310.                         //sw.Close();
  311.                     }
  312.                 }
  313.                 while (ret == NT_STATUS.STATUS_INFO_LENGTH_MISMATCH);
  314.             }
  315.  
  316.             #endregion
  317.  
  318.             #region IEnumerable Members
  319.  
  320.             System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
  321.             {
  322.                 return GetEnumerator();
  323.             }
  324.  
  325.             #endregion
  326.         }
  327.  
  328.         #region Private Members
  329.  
  330.         private static bool GetFileNameFromHandle(IntPtr handle, int processId, out string fileName)
  331.         {
  332.             IntPtr currentProcess = NativeMethods.GetCurrentProcess();
  333.             bool remote = (processId != NativeMethods.GetProcessId(currentProcess));
  334.             SafeProcessHandle processHandle = null;
  335.             SafeObjectHandle objectHandle = null;
  336.             try
  337.             {
  338.                 if (remote)
  339.                 {
  340.                     processHandle = NativeMethods.OpenProcess(ProcessAccessRights.PROCESS_DUP_HANDLE, true, processId);
  341.                     if (NativeMethods.DuplicateHandle(processHandle.DangerousGetHandle(), handle, currentProcess, out objectHandle, 0, false, DuplicateHandleOptions.DUPLICATE_SAME_ACCESS))
  342.                     {
  343.                         handle = objectHandle.DangerousGetHandle();
  344.                     }
  345.                 }
  346.                 return GetFileNameFromHandle(handle, out fileName, 200);
  347.             }
  348.             finally
  349.             {
  350.                 if (remote)
  351.                 {
  352.                     if (processHandle != null)
  353.                     {
  354.                         processHandle.Close();
  355.                     }
  356.                     if (objectHandle != null)
  357.                     {
  358.                         objectHandle.Close();
  359.                     }
  360.                 }
  361.             }
  362.         }
  363.         private static bool GetFileNameFromHandle(IntPtr handle, out string fileName, int wait)
  364.         {
  365.             using (FileNameFromHandleState f = new FileNameFromHandleState(handle))
  366.             {
  367.                 ThreadPool.QueueUserWorkItem(new WaitCallback(GetFileNameFromHandle), f);
  368.                 if (f.WaitOne(wait))
  369.                 {
  370.                     fileName = f.FileName;
  371.                     return f.RetValue;
  372.                 }
  373.                 else
  374.                 {
  375.                     fileName = string.Empty;
  376.                     return false;
  377.                 }
  378.             }
  379.         }
  380.  
  381.         private class FileNameFromHandleState : IDisposable
  382.         {
  383.             private ManualResetEvent _mr;
  384.             private IntPtr _handle;
  385.             private string _fileName;
  386.             private bool _retValue;
  387.  
  388.             public IntPtr Handle
  389.             {
  390.                 get
  391.                 {
  392.                     return _handle;
  393.                 }
  394.             }
  395.  
  396.             public string FileName
  397.             {
  398.                 get
  399.                 {
  400.                     return _fileName;
  401.                 }
  402.                 set
  403.                 {
  404.                     _fileName = value;
  405.                 }
  406.  
  407.             }
  408.  
  409.             public bool RetValue
  410.             {
  411.                 get
  412.                 {
  413.                     return _retValue;
  414.                 }
  415.                 set
  416.                 {
  417.                     _retValue = value;
  418.                 }
  419.             }
  420.  
  421.             public FileNameFromHandleState(IntPtr handle)
  422.             {
  423.                 _mr = new ManualResetEvent(false);
  424.                 this._handle = handle;
  425.             }
  426.  
  427.             public bool WaitOne(int wait)
  428.             {
  429.                return _mr.WaitOne(wait, false);
  430.             }
  431.  
  432.             public void Set()
  433.             {
  434.                 _mr.Set();
  435.             }
  436.             #region IDisposable Members
  437.  
  438.             public void Dispose()
  439.             {
  440.                 if (_mr != null)
  441.                     _mr.Close();
  442.             }
  443.  
  444.             #endregion
  445.         }
  446.  
  447.         private static void GetFileNameFromHandle(object state)
  448.         {
  449.             FileNameFromHandleState s = (FileNameFromHandleState)state;
  450.             string fileName;
  451.             s.RetValue = GetFileNameFromHandle(s.Handle, out fileName);
  452.             s.FileName = fileName;
  453.             s.Set();
  454.         }
  455.  
  456.         private static bool GetFileNameFromHandle(IntPtr handle, out string fileName)
  457.         {
  458.             IntPtr ptr = IntPtr.Zero;
  459.             RuntimeHelpers.PrepareConstrainedRegions();
  460.             try
  461.             {
  462.                 int length = 0x200;  // 512 bytes
  463.                 RuntimeHelpers.PrepareConstrainedRegions();
  464.                 try { }
  465.                 finally
  466.                 {
  467.                     // CER guarantees the assignment of the allocated 
  468.                     // memory address to ptr, if an ansynchronous exception 
  469.                     // occurs.
  470.                     ptr = Marshal.AllocHGlobal(length);
  471.                 }
  472.                 NT_STATUS ret = NativeMethods.NtQueryObject(handle, OBJECT_INFORMATION_CLASS.ObjectNameInformation, ptr, length, out length);
  473.                 if (ret == NT_STATUS.STATUS_BUFFER_OVERFLOW)
  474.                 {
  475.                     RuntimeHelpers.PrepareConstrainedRegions();
  476.                     try { }
  477.                     finally
  478.                     {
  479.                         // CER guarantees that the previous allocation is freed,
  480.                         // and that the newly allocated memory address is 
  481.                         // assigned to ptr if an asynchronous exception occurs.
  482.                         Marshal.FreeHGlobal(ptr);
  483.                         ptr = Marshal.AllocHGlobal(length);
  484.                     }
  485.                     ret = NativeMethods.NtQueryObject(handle, OBJECT_INFORMATION_CLASS.ObjectNameInformation, ptr, length, out length);
  486.                 }
  487.                 if (ret == NT_STATUS.STATUS_SUCCESS)
  488.                 {
  489.                     fileName = Marshal.PtrToStringUni((IntPtr)((int)ptr + 8), (length - 9) / 2);
  490.                     return fileName.Length != 0;
  491.                 }
  492.             }
  493.             finally
  494.             {
  495.                 // CER guarantees that the allocated memory is freed, 
  496.                 // if an asynchronous exception occurs.
  497.                 Marshal.FreeHGlobal(ptr);
  498.             }
  499.  
  500.             fileName = string.Empty;
  501.             return false;
  502.         }
  503.  
  504.         private static bool GetHandleType(IntPtr handle, int processId, out SystemHandleType handleType)
  505.         {
  506.             string token = GetHandleTypeToken(handle, processId);
  507.             return GetHandleTypeFromToken(token, out handleType);
  508.         }
  509.  
  510.         private static bool GetHandleType(IntPtr handle, out SystemHandleType handleType)
  511.         {
  512.             string token = GetHandleTypeToken(handle);
  513.             return GetHandleTypeFromToken(token, out handleType);
  514.         }
  515.  
  516.         private static bool GetHandleTypeFromToken(string token, out SystemHandleType handleType)
  517.         {
  518.             for (int i = 1; i < handleTypeTokenCount; i++)
  519.             {
  520.                 if (handleTypeTokens[i] == token)
  521.                 {
  522.                     handleType = (SystemHandleType)i;
  523.                     return true;
  524.                 }
  525.             }
  526.             handleType = SystemHandleType.OB_TYPE_UNKNOWN;
  527.             return false;
  528.         }
  529.  
  530.         private static string GetHandleTypeToken(IntPtr handle, int processId)
  531.         {
  532.             IntPtr currentProcess = NativeMethods.GetCurrentProcess();
  533.             bool remote = (processId != NativeMethods.GetProcessId(currentProcess));
  534.             SafeProcessHandle processHandle = null;
  535.             SafeObjectHandle objectHandle = null;
  536.             try
  537.             {
  538.                 if (remote)
  539.                 {
  540.                     processHandle = NativeMethods.OpenProcess(ProcessAccessRights.PROCESS_DUP_HANDLE, true, processId);
  541.                     if (NativeMethods.DuplicateHandle(processHandle.DangerousGetHandle(), handle, currentProcess, out objectHandle, 0, false, DuplicateHandleOptions.DUPLICATE_SAME_ACCESS))
  542.                     {
  543.                         handle = objectHandle.DangerousGetHandle();
  544.                     }
  545.                 }
  546.                 return GetHandleTypeToken(handle);
  547.             }
  548.             finally
  549.             {
  550.                 if (remote)
  551.                 {
  552.                     if (processHandle != null)
  553.                     {
  554.                         processHandle.Close();
  555.                     }
  556.                     if (objectHandle != null)
  557.                     {
  558.                         objectHandle.Close();
  559.                     }
  560.                 }
  561.             }
  562.         }
  563.  
  564.         private static string GetHandleTypeToken(IntPtr handle)
  565.         {
  566.             int length;
  567.             NativeMethods.NtQueryObject(handle, OBJECT_INFORMATION_CLASS.ObjectTypeInformation, IntPtr.Zero, 0, out length);
  568.             IntPtr ptr = IntPtr.Zero;
  569.             RuntimeHelpers.PrepareConstrainedRegions();
  570.             try
  571.             {
  572.                 RuntimeHelpers.PrepareConstrainedRegions();
  573.                 try { }
  574.                 finally
  575.                 {
  576.                     ptr = Marshal.AllocHGlobal(length);
  577.                 }
  578.                 if (NativeMethods.NtQueryObject(handle, OBJECT_INFORMATION_CLASS.ObjectTypeInformation, ptr, length, out length) == NT_STATUS.STATUS_SUCCESS)
  579.                 {
  580.                     return Marshal.PtrToStringUni((IntPtr)((int)ptr + 0x60));
  581.                 }
  582.             }
  583.             finally
  584.             {
  585.                 Marshal.FreeHGlobal(ptr);
  586.             }
  587.             return string.Empty;
  588.         }
  589.  
  590.         private static bool ConvertDevicePathToDosPath(string devicePath, out string dosPath)
  591.         {
  592.             EnsureDeviceMap();
  593.             int i = devicePath.Length;
  594.             while (i > 0 && (i = devicePath.LastIndexOf('\\', i - 1)) != -1)
  595.             {
  596.                 string drive;
  597.                 if (deviceMap.TryGetValue(devicePath.Substring(0, i), out drive))
  598.                 {
  599.                     dosPath = string.Concat(drive, devicePath.Substring(i));
  600.                     return dosPath.Length != 0;
  601.                 }
  602.             }
  603.             dosPath = string.Empty;
  604.             return false;
  605.         }
  606.  
  607.         private static void EnsureDeviceMap()
  608.         {
  609.             if (deviceMap == null)
  610.             {
  611.                 Dictionary<string, string> localDeviceMap = BuildDeviceMap();
  612.                 Interlocked.CompareExchange<Dictionary<string, string>>(ref deviceMap, localDeviceMap, null);
  613.             }
  614.         }
  615.  
  616.         private static Dictionary<string, string> BuildDeviceMap()
  617.         {
  618.             string[] logicalDrives = Environment.GetLogicalDrives();
  619.             Dictionary<string, string> localDeviceMap = new Dictionary<string, string>(logicalDrives.Length);
  620.             StringBuilder lpTargetPath = new StringBuilder(MAX_PATH);
  621.             foreach (string drive in logicalDrives)
  622.             {
  623.                 string lpDeviceName = drive.Substring(0, 2);
  624.                 NativeMethods.QueryDosDevice(lpDeviceName, lpTargetPath, MAX_PATH);
  625.                 localDeviceMap.Add(NormalizeDeviceName(lpTargetPath.ToString()), lpDeviceName);
  626.             }
  627.             localDeviceMap.Add(networkDevicePrefix.Substring(0, networkDevicePrefix.Length - 1), "\\");
  628.             return localDeviceMap;
  629.         }
  630.  
  631.         private static string NormalizeDeviceName(string deviceName)
  632.         {
  633.             if (string.Compare(deviceName, 0, networkDevicePrefix, 0, networkDevicePrefix.Length, StringComparison.InvariantCulture) == 0)
  634.             {
  635.                 string shareName = deviceName.Substring(deviceName.IndexOf('\\', networkDevicePrefix.Length) + 1);
  636.                 return string.Concat(networkDevicePrefix, shareName);
  637.             }
  638.             return deviceName;
  639.         }
  640.  
  641.         #endregion
  642.     }
  643. }
Apr 30 '09 #7
robbietapping
5 New Member
btw, removed the namespace at the start, as you may have issues at runtime calling the class, and or at build time..

Cheers

Robbie
Apr 30 '09 #8
aumsoft
2 New Member
@robbietapping
I am using your C# library to check that file is open or not from my application. Everything works fine but it gives below error:
"ObjectDisposedException: Safe handle has been closed"
After getting this exception i am not able to end application process even in task manager by calling end Process. I have refered all the code in class but not able to identify where it uses disposed object again.
1) How to resolve this error?
2) This function works only on Xp machine. When i test this code on vista64bit, OpenFiles enumerator gives nothing value.
Apr 27 '10 #9
Frinavale
9,735 Recognized Expert Moderator Expert
Have you considered using the File.Exists() method to check to see the file exists?

It's pretty easy to use and is included as part of the .NET Framework.


-Frinny
Apr 27 '10 #10
aumsoft
2 New Member
Hi frinavale....

Sorry to not explained well my question but i am looking for to check whether the file is open or not by other process included notepad, paint etc. I dont want check that file is exist or not. By the way we have resolve the issue of exception of "ObjectDisposedException: Safe handle has been closed". But after using this function we are not able to end/close the application even in from task manager by calling end process. Also awaiting for solution to run on vista64 OS.

Regards
Apr 28 '10 #11

Sign in to post your reply or Sign up for a free account.

Similar topics

23
by: David McCulloch | last post by:
QUESTION-1: How can I detect if Norton Internet Security is blocking pop-ups? QUESTION-2a: How could I know if a particular JavaScript function has been declared? QUESTION-2b: How could I...
2
by: FE | last post by:
Hi, I need to create a program that will connect a media stream (a server on the internet - Windows Media format) and then generate an error when : * The stream is ok but there is no sound...
0
by: David Buckley | last post by:
I remember seeing an app on a site that had the basic look and feel of media centre i was wanting to find the app again to start buidling a media centre for a home project can anyone point me in...
0
by: David Buckley | last post by:
I remember seeing a small example on gotdotnet about a year ago it was done in c# 1.1 and it showed you how to make forms appear like media centre is their a component or if anyone knows of where...
2
by: =?Utf-8?B?U3UgbmVpbA==?= | last post by:
My media centre will only let me create data dvd's and not slideshow dvd's can anyone help with a solution. I have a dell dimension 9150 and media centre 2005
4
by: OrchidNut | last post by:
Hi, need to have a new notebook and want to avoid Vista. XP pro is my favourite but hard to get on a notebook. I can get XP Media Centre 2005 but not interested in entertainment. Is it...
0
by: =?Utf-8?B?Q2hyaXNzaWUgUg==?= | last post by:
Help! Would you believe have just bought my first MP3 player (mind you I am in my fifties). Although not a computer whizz - I manage to do most things on my PC. Loaded CDs onto Windows Media...
1
by: dgb09 | last post by:
Hi guys, Im trying to write a program in C++ using windows with an interface that is similar to either media centre or sony's XMB where there are 3 layers of menus, with the lower 2 layers driven...
36
by: Don | last post by:
I wrote an app that alerts a user who attempts to open a file that the file is currently in use. It works fine except when the file is opened by Notepad. If a text file is opened, most computers...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
1
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
1
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...
0
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and...
0
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The...
0
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated ...
0
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.