tldr:
I have one function that draws image that I save later.
I can save file in every possible scenario except when I drag image to exe while that image is not in the same folder. Dragged image just feeds string path to the function.
/tldr
I have a function that draws image in Picture Box on Windows Forms.
This function accepts string - path, and then processes the data.
When user drops picture on form, I send path from dropped file to my function and it draws file just fine.
Then I hit save button which contains next code :
Bitmap tmpOutputSave = new Bitmap(pbOutput.Image);
tmpOutputSave.Save("Generisano\\Image" + tmpDate + ".png", System.Drawing.Imaging.ImageFormat.Png);
And I save the image.
Everything works fine.
If I open my application in D:\some_path\MyApplication\myapp.exe and I drag image file from Desktop, I will see the image in picturebox, and when I hit save - everything works fine.
If I drag image file from same folder to myapp.exe, and hit save - everything works fine too, and I can see the image in picturebox.
However, in this second case, if I drag image from any other folder to myapp.exe, image will load as well but when I try to save I will get "Generic error in GDI+".
Code that I'm using to get path from dragged file to exe is :
program.cs
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main(string[] args)
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1(args));
}
}
form1.cs
public Form1(string[] args) {
InitializeComponent();
sablon = new Sablon(this);
LoadSettings();
pbOutput.MouseWheel += pbOutput_MouseWheel;
if (args.Count() > 0) {
try
{
imgPath = args[0];
pbOutput.Image = Crtaj.Sliku(imgPath);
hadFirstArgument = true;
}
catch (Exception e)
{
MessageBox.Show("Error : " + e.Message);
}
}
}
Notes : Crtaj.Sliku is : Class : Crtaj, with function Sliku - which accepts string to draw image.
So to sum up :
- It's the same function for all cases
- Dragging on form from any location works fine
- Dragging on exe from same folder works fine
- Dragging on exe from another folder doesn't work
- Paths are same in all cases, image is same in all cases
Only difference is that I try to drag and drop file from another folder on exe (no problem if I do it on form, even though code and paths are the same).
I saw many topics about this, but I didn't really see specific issue related to mine, I'm sorry if I oversaw something.
What could be the problem ?
I'm sure that it's not illegal characters or file location - because I format characters before saving, I'm sure that folder exists and paths are the same too.
Thank you!
Can you try it using an absolute path? Like setting the savefile location to somewhere like;
C:\Temp\Test.png
Or somewhere that you know exists. If you're generating the save path (even if it's with the same code), the resulting folders might be different in your two cases, and it may fail to save the file because of that. I remember losing some hair because of that a few years ago. If that happens to be the case, you'll only need to look into why the generated path points to an incorrect location.
Related
This really does not make any sense. I have a UWP application, titled FirstUWP. It opens fine on its own.
I have a desktop extension that I made called scrren.exe, taking advantage of tesseract to read some image from the screen. When first opening my UWP and then opening up the scrren.exe on it's own, both run fine.
However, when I use the runfulltrust launcher from UWP, the scrren.exe cannot write to a file that is under the UWP's project.
When they are launched entirely separately, the scrren.exe can write to the folder fine, it is just when the UWP launches it the scrren.exe cannot write to the folder within the UWP.
This code is the place where the problem occurs within the Desktop Extension sccren.exe. I've also attached a screenshot showing the Assets tree within the UWP, showing the Images folder which seems to be where my problems originate. Below that, I attached a screenshot showing what I mean that when launched from within UWP, scrren.exe shows up under the UWPs parent name, but this is where I get errors and scrren.exe cannot write to the Images folder.
I really hope this makes sense.
string result = Assembly.GetExecutingAssembly().Location;
int index = result.LastIndexOf("\\");
string rootPath = $"{result.Substring(0, index)}\\..\\";
using (Bitmap bitmap1 = new Bitmap(bounds.Width, bounds.Height))
{
using (Graphics g = Graphics.FromImage(bitmap1))
{
g.CopyFromScreen(Point.Empty, Point.Empty, bounds.Size);
}
try
{
using (bitmap1)
{
bitmap1.Save((rootPath + #"Scrn\Images\test.png"), System.Drawing.Imaging.ImageFormat.Png);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message + "Right here");
}
// Sleep for one second in order to let the file properly save
Thread.Sleep(1000);
}
You can't write to a packaged app's install location; it is read-only. Instead you should be using ApplicationData.Current.LocalFolder to get the local folder for saving files.
Also make sure you are using FullTrustProcessLauncher to launch your exe, not something like Process.Start().
I'm using IwishRuntime Library to create shortcuts dynamically. Setting Icon location won't work if the icon is in a network path.
For Example if the path is something like "\\ServerName\Folder\Resources\Userguide.ico"; the icon won't be set.
This happens only in windows 8 and 8.1. It works fine in prior operating systems.
Is there any workaround to fix this.
string path = System.IO.Directory.GetCurrentDirectory() + #"\Upgrade\Resources\userguide.ico";
//Icon Location is set only if the file is there. If the file is not accessible due to security reasons
//Icon location is not set. The default program will be taken as the icon in this case.
if (System.IO.File.Exists(path))
{
shortcut.IconLocation = path;
}
Thanks.
You need to use an # in front of your Path and everytime \\
#"\\Network\\ExampleFolder"
Its working on Windows 10
I ran into a similar issue, Win10 creators edition. Conclusion was, Icon.ExtractAssociatedIcon() will not run from a network path.. It won't read the icon from the .ico file, my test...
Icon myImage;
string fn = sIconPath + "\\" + cSymbolIconFile;
try
{
if (File.Exists(fn)) myImage = Icon.ExtractAssociatedIcon(fn);
else MessageBox.Show("Error: File not found.");
} catch(Exception EE) { MessageBox.Show("Error: "+EE.Message); }
When my sIconPath is a network path, I get an exception saying "Error: Value of is not valid for 'filePath'"
Now to solve this, you should put the icon file in a Resource and include it in your link.
Create a Resource in a project "mydll" named e.g. "buttonresources", put your icon files into it ..
Put mydll.dll in the references of your executable main project
There should be a buttonresources.resx in your project now. Address an icon named e.g. "myicon" as follows..
System.Reflection.Assembly a1 = GetType().Assembly;
var m = new System.Resources.ResourceManager("mydll.buttonresources", a1);
Icon myImage = (System.Drawing.Icon)m.GetObject("myicon");
I have gotten a program Im working on to load some pictures and display them within a listview after using a openfiledialog. What I am looking to do now is take this one step further and auto-load the images from a directory 'icons' within the application directory. Im not too sure how to go about it, So Im going to paste my current code here, and work it from there...
private void loadImageLibraryToolStripMenuItem_Click(object sender, EventArgs e)
{
openFileDialog1.Multiselect = true;
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
if (openFileDialog1.FileNames != null)
{
for (int i = 0; i < openFileDialog1.FileNames.Length; i++)
{
addImage(openFileDialog1.FileNames[i]);
}
}
else
addImage(openFileDialog1.FileName);
}
}
private void addImage(string imageToLoad)
{
if (imageToLoad != "")
{
imageList1.Images.Add(Image.FromFile(imageToLoad));
listView1.BeginUpdate();
listView1.Items.Add(imageToLoad, baseValue++);
listView1.EndUpdate();
}
}
Edit to Clarify: The code provided shows how to load and show the images in a listview control. What Im looking to do now is upon starting the app, load the images automatically from a folder in the programs directory, and then display them in the listview.
Off the top of my head with no IDE so there may be mistakes! try this
var files = System.IO.Directory.GetFiles(System.IO.Path.GetDirectoryName(System.Windows.Forms.Application.ExecutablePath) + "\\icons")
files will be an array of strings containing all the files in the directory which you can then loop as you have above using the array
openFileDialog1.FileNames
The \ may not be required before icons, I can't remember if GetDirectoryName drops the trailing \ from the path or not.
you can also pass a filter to GetFiles to only return certain file types.
HTH
EDIT: I have edited the code above to use
System.Windows.Forms.Application.ExecutablePath
rather than
System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase
On testing the code now I have access to an IDE it seems the CodeBase property prepends the path with file:/// which caused my IDE to blow up with an error saying
URI formats are not supported
the code now works in my IDE, You need to make sure your icons Directory is in the same directory as your executable so in my case ....bin\debug\
Give this a try and if it still fails let me know!
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?
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.
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.
C#: How do you handle/parse messages for your applications like drag and dropping an associated file type?
Let's say I have a text document application and I want it to execute and open a file if,
1.) a .txt document is dragged on top of the exe.
How could I make that possible, to execute the text software, and two, finally open and display the text document in the text document software?
You have to find where your Main method is declared to be sure its signature includes the args parameter, then you can check upon args array and you will find the complete pathname of the file dragged on your application's exe. Now you can then work with it accordingly to your needs.
Example:
static void Main(String[] args)
{
string p = args[0];
string e = Path.GetExtension(p);
if (e == ".txt")
{
// It's a text file
}
}
You can also drag more than a file and find their names inside the same array.
Remember that in my example i don't check if there are actually some elements in args array and thus i can get an IndexOutOfBoundException if nothing is dragged (or passed as argument) when launching the application and finally that using Path.GetExtension method doesn't assure you the file is what you think, but just it has that extension.
When someone drags-and-drops a text file on your application's executable, your app will get started and the path of the text file will be passed as a parameter. You should be able to examine it in your Main method.