How to run an exe file in the same directory as the input file for a C# console application using VS2010?

How would you recode the attached C# Console application so that the executable can run in the same directory as the input file? Currently the exe runs fine as long as it is not in the same directory path as the input file. When I put the exe in the same directory as the input file, the Visual Studio Just-In-Time Debugger appears.
test.txt
zimmer9Asked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Fernando SotoRetiredCommented:
Hi zimmer9;

Instead of passing a path plus the filename just passed the filename without any path information something like the following.

string bankFilePath = "C.ard.out");

if (File.Exists(bankFilePath))
{
    File.Delete(bankFilePath);
}

Open in new window

0
Carl TawnSystems and Integration DeveloperCommented:
If you need to you can get the path the currently running EXE using:

string startupPath = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetEntryAssembly().Location);
0
Daniel Van Der WerkenIndependent ConsultantCommented:
Your problem is that you are reading in *all* the binary files in the current directory. This read includes the actual binary file that you are executing, and it is locked. You are getting a file access exception because the file is already in use (ReadBinary.EXE).

This includes all ReadBinary.* files, ReadBinary.PDB, ReadBinary.vshost.EXE, etc.

What you need to do is compare with what is running against what is in the current directory and *not* process the running files. Here is code that works for me:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace ReadBinary
{
    public static class MyGlobals
    {
        public static int intcheckOffset = 0;
        public const string BASE_DIR = @"C:\Users\Daniel\Documents\Visual Studio 2010\Projects\ReadBinary\ReadBinary\bin\Debug\";

    }



    class BinaryFileTest
    {
        public static string GetFileTitleOnly(string fileName)
        {
            string fileTitle = string.Empty;

            if (fileName.Contains('.'))
            {
                int startIndex = 0;
                int dotIndex = int.MinValue;

                if (fileName.Contains('\\'))
                {
                    startIndex = fileName.LastIndexOf('\\');
                }

                dotIndex = fileName.IndexOf('.');

                fileTitle = fileName.Substring(startIndex, dotIndex);
            }

            return fileTitle;
        }

        static void Main()
        {

            File.Open(MyGlobals.BASE_DIR + "C.ard", FileMode.Create).Close();

            System.Reflection.Assembly currentRunningAssembly = System.Reflection.Assembly.GetExecutingAssembly();         

            string errorFilePath = System.IO.Path.Combine(MyGlobals.BASE_DIR, "error.txt");
            string indFilePath = System.IO.Path.Combine(MyGlobals.BASE_DIR, "C.ard.ind");
            string bankFilePath = System.IO.Path.Combine(MyGlobals.BASE_DIR, "C.ard.out");
            {
                File.Delete(errorFilePath);
            }

            //delete the bank output file if it presently exists so that a new bank output file can be created in the event any errors are discovered
            if (File.Exists(indFilePath))
            {
                File.Delete(indFilePath);
            }


            if (File.Exists(bankFilePath))
            {
                File.Delete(bankFilePath);
            }

            //foreach (string f in tiffList)
            //{
            //    File.Delete(f);
            //}


            DirectoryInfo parentDirectory = new DirectoryInfo(MyGlobals.BASE_DIR);

            foreach (FileInfo file in parentDirectory.GetFiles())
            {
                if (!string.Equals(file.Name, "C.ard", StringComparison.InvariantCultureIgnoreCase) &&
                    !string.Equals(GetFileTitleOnly(file.Name), GetFileTitleOnly(currentRunningAssembly.ManifestModule.Name), StringComparison.InvariantCultureIgnoreCase))
                {
                    StreamWriter sw1 = new StreamWriter(errorFilePath);
                    ProcessFile(file.FullName, sw1);
                    ProcessFileBinary(file.FullName, sw1);
                }
            }

            if (File.Exists(errorFilePath))
            {
                if (new FileInfo(errorFilePath).Length == 0)
                {
                    if (File.Exists(errorFilePath))
                    {
                        File.Delete(errorFilePath);
                    }
                }
            }
        }

        private static void ProcessFile(string filePath, StreamWriter sw1)
        {
            var anchor1 = Encoding.UTF8.GetBytes("66ELRC");
            var anchor2 = Encoding.UTF8.GetBytes("II*");
            List<byte[]> result = new List<byte[]>();

            var bytes = File.ReadAllBytes(filePath);

            for (int i = 0; i < bytes.Length; i++)
            {

                var data = bytes.Skip(i).Take(anchor1.Length);
                if (data.SequenceEqual(anchor1))
                {
                    for (int k = i + anchor1.Length; k < bytes.Length; k++)
                    {
                        var data2 = bytes.Skip(k).Take(anchor2.Length);
                        if (data2.SequenceEqual(anchor2))
                        {
                            var res = bytes.Skip(i).Take(k - i).ToArray();
                            result.Add(res);
                            i = k;
                            break;
                        }
                    }
                    sw1.Close();
                }
            }
        }

        private static void ProcessFileBinary(string filePath, StreamWriter sw1)
        {

            using (var f = File.Open(filePath, FileMode.Append))
            {
                byte[] buf = new byte[] { 53, 53, 69, 76, 82, 67 };
                f.Write(buf, 0, buf.Length);
            }

            var anchor1 = Encoding.UTF8.GetBytes("II*");
            var anchor2 = Encoding.UTF8.GetBytes("55ELRC");
            List<byte[]> result1 = new List<byte[]>();
            var bytes = File.ReadAllBytes(filePath);

            for (int i = 0; i < bytes.Length; i++)
            {
                var data = bytes.Skip(i).Take(anchor1.Length);
                if (data.SequenceEqual(anchor1))
                {
                    for (int k = i + anchor1.Length; k < bytes.Length; k++)
                    {
                        var data2 = bytes.Skip(k).Take(anchor2.Length);
                        if (data2.SequenceEqual(anchor2))
                        {
                            var res = bytes.Skip(i).Take(k - i).ToArray();
                            result1.Add(res);
                            i = k;
                            break;
                        }
                    }
                }
            }

            string bankFilePath = System.IO.Path.Combine(MyGlobals.BASE_DIR, "C.ard.out");
            using (FileStream fs = new FileStream(bankFilePath, FileMode.Create))
            {
                using (BinaryWriter bwrite = new BinaryWriter(fs))
                {
                    foreach (var arr in result1)
                    {
                        bwrite.Write(arr);
                    }
                }
            }
            sw1.Close();
        }
    }
}

Open in new window

0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
C#

From novice to tech pro — start learning today.