blah blah blah is here! blah blah » Close

up0down
link

The basic way I want this to work is this:
1. Program asks user for a process name: string pname.
2. Program searches computer for an executable file that contains pname.
3. Program executes that file.
How do I do this?

last answered 2 years ago

1 answers

up0down
link

If you're using .NET 2.0 or later, then this should work:
using System;
using System.IO;
using System.Diagnostics;
class Program
{
static void Main()
{
FindAndExecuteFile(@"C:\","notepad.exe"); // say
Console.ReadKey(); // press any key to exit
}
static void FindAndExecuteFile(string startDir, string fileName)
{
string[] files = Directory.GetFiles(startDir, fileName,
SearchOption.AllDirectories);
if (files.Length > 0)
{
Process.Start(files[0]);
}
else
{
Console.WriteLine("{0} could not be found in {1}", fileName,
startDir);
}
}
}
Clearly, the more you can 'refine' the start directory for beginning the search, the quicker the code will work.

up0down
link

HI
Thanks for your code that had helped me a lot but i am geting a exception in one thing i.e Access to the path 'D:\System Volume Information' is denied. So can you please tell me the solution for this.
pls reply me to manoj22184@gmail.com
Thanks ,
M.MANOJ.

up0down
link

I think you'll just have to exclude that particular directory from consideration. The code to do that is a bit messy but try this method:
static void FindAndExecuteFile(string startDir, string fileName)
{
string[] files = Directory.GetFiles(startDir, fileName,
SearchOption.TopDirectoryOnly);
if (files.Length > 0)
{
Process.Start(files[0]);
return;
}
bool found = false;
string[] directories = Directory.GetDirectories(startDir, "*", SearchOption.TopDirectoryOnly);
foreach(string directory in directories)
{
if (!directory.Contains("System Volume Information"))
{
files = Directory.GetFiles(directory, fileName, SearchOption.AllDirectories);
if (files.Length > 0)
{
Process.Start(files[0]);
found = true;
break;
}
}
}
if (!found)
{
Console.WriteLine("{0} could not be found in {1}", fileName, startDir);
}
}

up0down
link

I need only File searching. if I have that file in a certain directory, the program returns "1" else it returns "0"..how can I do that?

up0down
link

If you only want to search the directory itself for a given file and not any subdirectories, then this method should do it:
static int FindFile(string directoryName, string fileName)
{
string[] files = new string[0]; // empty array
try
{
files = Directory.GetFiles(directoryName, fileName, SearchOption.TopDirectoryOnly);
}
catch
{
return -1;
}
return (files.Length > 0) ? 1 : 0;
}
If an exception occurs (for example the directory doesn't exist), the method will simply return -1 though you could, of course, handle this differently depending on your needs.

This post was imported from csharpfriends, if you have a similiar question please ask it again.

All previous members have been migrated, hope you enjoy the new platform!

Feedback