Anwendung zu einer Datei herausfinden

LordDeath

Erfahrenes Mitglied
Hi

Wie krieg ich die Anwendung mit Pfad zu einer Dateiendung heraus?
Sample:

test.doc --> C:\Program Files\Microsoft Office\OFFICE11\winword.exe

Greetz
 
Hab dir ne Klasse geschrieben... ;-)

C#:
using System;
using Microsoft.Win32;

namespace yanick.utils
{
    /// <summary>
    /// @autor Yanick Dickbauer
    /// 
    /// A Util-Class that contains informations about Windows File Extensions
    /// </summary>
    /// <remarks>
    /// This Class access to the Windows Registration and its only tested with Windows XP Home Edition
    /// </remarks>
    public class FileExtensions
    {
        /// <summary>
        /// Finds out the Program that should execute the File with the File Extension <paramref name="fileExt"/>
        /// </summary>
        /// <param name="fileExt">
        /// The Extensions that should be searched (without a point)
        /// Sample: "mp3"; NOT: ".mp3"!
        /// </param>
        /// <returns>
        /// The path of the Program that should execute the File.
        /// If the File Extension is not registrated it returns a null-Pointer
        /// </returns>
        public static String getFileExecuter (String fileExt)
        {
            //Open the Registry-Key in which the FileExecuters are saved
            RegistryKey key = Registry.CurrentUser;
            key = key.OpenSubKey(subKeyName + "\\." + fileExt+"\\OpenWithList");
            if (key == null)
                return null;

            //Fetch the Program Path that is normally saved in the key "a"
            //"a" is the standard Program to execute the file
            object oValue = key.GetValue("a");
            if (oValue == null || !(oValue is String))
                return null;

            return ((String) oValue);
        }
        
        /// <summary>
        /// Finds out the Program that should execute the File<paramref name="fileName"/>
        /// </summary>
        /// <param name="fileName">The File Name</param>
        /// <returns>
        /// The File Executer Program that could open the File <paramref name="fileName"/>
        /// </returns>
        /// <see cref="getFileExecuter(String)"/>
        public static String getFileExecuterByFileName(String fileName)
        {
            if (!fileName.Contains("."))
                throw new ArgumentException("The File Name doesn't contain a File Extension", fileName);
            
            String[] splitten = fileName.Split('.');
            return getFileExecuter(splitten[splitten.Length - 1]);
        }
        
        private const String subKeyName = "Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\FileExts";
    }
}

und Tests erfolgreich überstanden *g*

C#:
    [TestFixture]
    public class TestFileExtensions
    {
        [Test]
        public void TestGetExecuter()
        {
            String fileExecuter = FileExtensions.getFileExecuter("mp3");
            if (fileExecuter == null)
                Console.WriteLine("Kein Programm Gefunden, das den Dateitypen >>mp3<< "+
                                  "öffnen könnte.");
            else
                Console.WriteLine("Folgendes Programm könnte den Dateitypen >>mp3<< " +
                                  "öffnen: {0}", fileExecuter);
        }
        
        [Test]
        public void TestGetExecuterByFileName()
        {
            String fileExecuter = FileExtensions.getFileExecuterByFileName("C\\MeineMusik\\hallo.mp3");
            if (fileExecuter == null)
                Console.WriteLine("Kein Programm Gefunden, das den Dateitypen >>mp3<< " +
                                  "öffnen könnte.");
            else
                Console.WriteLine("Folgendes Programm könnte den Dateitypen >>mp3<< " +
                                  "öffnen: {0}", fileExecuter);
        }
    }

Ausgabe 1: Folgendes Programm könnte den Dateitypen >>mp3<< öffnen: Winamp.exe
Ausgabe 2: Folgendes Programm könnte den Dateitypen >>mp3<< öffnen: Winamp.exe

Lg, Yanick
 
Zuletzt bearbeitet:
Hi
Besten Dank funktioniert einwandfrei.
Aber leider nur bei Anwendungen die in den Path variablen eingetragen sind.
Bsp: doc --> Word
Wo es nicht geht zum Beispiel ist ace --> Winace.

Hast du eine Idee wie ich zu dem Programm noch den Pfad zur winace.exe rauskriegst?

Greetz
 
Zuletzt bearbeitet:
Hm... das ist ne gute Frage..

Eigentlich müsste ja der volle Pfad auch irgendwo in der Registry gespeichert sein...

Im schlimmsten Fall (ist zwar ein bisschen unschön..) müsstest diese Datei dann im FileSystem suchen damit du den vollen Pfad rausbekommst, fragt sich halt ob du dir diesen Geschwindigkeitsverlust leisten kannst *g*

Lg, Yanick
 
Nö die Zeit ist für mich und den Auftraggeber unakzeptabel, weil man dann ja alle Festplatten aufm System durchsuchen müsste. Und bei ner fast vollen 80GB Platte dauert das dann doch zu lange.

Wenn ich ne Lösung gefunden hab poste ich Sie hier.

EDIT: Ok Lösung gefunden

C#:
/// <summary>
/// Gets the executer application of an given file extension.
/// </summary>
/// <param name="fileExtension">The file extension without a dot.</param>
/// <returns>The application to execute the file</returns>
/// <exception>Excpetion if the extension not found or if no program is found to open file</exception>
public static string getExecuterApplication(string fileExtension)
{
	string _ret = string.Empty;
	RegistryKey _regKey = Registry.ClassesRoot;
	_regKey = _regKey.OpenSubKey("." + fileExtension);
	if(_regKey == null)
	{
		throw new Exception("Extension " + fileExtension + " not found!");
	}
	else
	{
		object _obj = _regKey.GetValue("");
		_regKey.Close();
		_regKey = Registry.ClassesRoot;
		_regKey = _regKey.OpenSubKey(_obj.ToString() + "\\shell\\Open\\command");
	        if(_regKey == null)
		{
			throw new Exception("Extension " + fileExtension + " has no starting program!");
		}
		else
		{
			_obj = _regKey.GetValue("");
			_regKey.Close();
		
			_ret = _obj.ToString();
			if(_ret.StartsWith("\""))
			{
				_ret = _ret.Remove(0, 1);
				_ret = _ret.Substring(0, _ret.IndexOf("\""));
			}
			else
			{
				_ret = _ret.Substring(0, _ret.IndexOf(" "));
			}
		}
	}
	return _ret;
}

Greetz
 
Zuletzt bearbeitet von einem Moderator:
Zurück