views:

136

answers:

2

I have a program I have written in C#, which loads an image with Image.FromFile, and it loads the image successfully every time. However, when you drag and drop another file on the executable, like you are giving the program the command line argument of the file, and the file is not in the same folder as the executable, the program crashes because it says the path to the file does not exist, even though it does.

I think that by dropping a file on the executable, it's changing the path it's loading images from somehow. How can I fix this problem?

+1  A: 

Your program would be started with a different Environment.CurrentDirectory. Always make sure you load files with an absolute path name (i.e. don't use Image.FromFile("blah.jpg")).

To get the absolute path to a file that's stored in the same directory as your EXE, you could use Application.StartupPath for example. Or Assembly.GetEntryAssembly().Location if you don't use Windows Forms.

Hans Passant
A: 

It depends on how you are initiating the file drag outside of your application. If you click and drag a file from Windows Explorer, the full absolute path name is included in the drop. In this case the following code shows the filename and performs a drop of the file's contents into a textbox:

private void textBox1_DragEnter(object sender, DragEventArgs e)
{
    if (e.Data.GetDataPresent(DataFormats.FileDrop))
        e.Effect = DragDropEffects.Copy;
}

private void textBox1_DragDrop(object sender, DragEventArgs e)
{
    if (e.Data.GetDataPresent(DataFormats.FileDrop))
    {
        var objPaths = (string[])(e.Data.GetData(DataFormats.FileDrop));
        if (objPaths != null && objPaths.Length > 0 && File.Exists(objPaths[0]))
        {
            MessageBox.Show(string.Format("Filename: {0}", objPaths[0]));
            using (TextReader tr = new StreamReader(objPaths[0]))
                textBox1.Text = tr.ReadToEnd();
        }
    }
}

So let us know more about your drag source. Most likely you will have to modify your source to drag the absolute path, or somehow determine the full path from the relative path in the drag data.

Also, your program should never crash due to bad data. Either check for the required conditions, or use a try/catch block around the necessary code.

Simon Chadwick