Refrain from using local path for image in C# - c#

I am loading an image in my program with this code:
Image img = new Bitmap(#"C:\Users\******\Desktop\*****\bin\Debug\image.png");
I would like to keep the location static so I don't have to manually edit the path when I run the program on a different PC.
I am experimenting with the apps.config file as I have heard this is where my solution will lie.
Any help with this would be appreciated!

Why not use Environment.SpecialFolder?
This isn't static, obviously, but you wouldn't have to edit anything. You would really only have to create the folders on the desktop if they don't already exist.
string path = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
Or use System.Environment.CurrentDirectory since it looks like that's where you're putting it anyway...
Image img = new Bitmap(Environment.CurrentDirectory + #"\image.png");

A better solution would be to embed it in a resx file as part of your assembly. That way you wouldn't have to worry about the file being located any differently.

The static property
AppDomain.CurrentDomain.BaseDirectory
points to the path from where the application was started, even if the current directory points somewhere else. You can use this to locate files that are in the same directory as the executable. However, for small images (i.e. GUI components), embedding them as resources is the way to go.

Related

How to pass relative path to use the File.Delete static function in C#?

I've been trying to create a way to upload, download and delete a PDF file. The upload and the download function work fine, but when I try to delete the PDF it doesn't really work as I want it to.
It does work when I use this form:
File.Delete(#"C:\Users\Donovan\1_Test.pdf");
But it doesn't work when I try this:
File.Delete(#"~\1_Test.pdf");
I want to find a way to make the second line of code work, because I work in a team and we don't share the same file path.
Use Environment.GetFolderPath to find the user's home directory.
string home = Environment.GetFolderPath(Environment.SpecialFolder.UseProfile);
File.Delete(Path.Combine(home, "1_Test.pdf"));
You might also want to consider putting the file in the folder for temporary files instead. You can find that location with Path.GetTempPath. (Note that windows will not automatically clean up temporary files, so you still need to delete anything you put there after you are done with it.)
Try this. I think it works :D
File.Delete(Server.MapPath("~/") + "1_Test.pdf");
If you are all using the userpath you can go with this approach:
System.IO.File.Delete(
Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.UserProfile),
"1_Test.pdf"
)
);
You unfortunately cannot make it work with ~. This only works as a relative path for web applications.
We use a local config file for our application where each developer stores its own preferences and can change these independent of other developers.
Depending on your application (web, desktop, mobile, windows, linux, whatever) you can write a config-object and fill it or use i.e. appsettings in web.config for this purpose.
var basePath = Config.FileBase;
File.Delete(Path.Combine(basePath, "\1_Test.pdf"));
Another method:
File.Delete(Environment.ExpandEnvironmentVariables("%USERPROFILE%\\1_Test.pdf"));
Have you considered it to put the *.pdf files in a database?

Change pictureBox.Image with c# = FileNotFoundException

i have a small app in C# winform. It work great but i don't understand how to change the image of a picture box in code :
i have this directory for my image :
myProjectDirectory/bin/Pics/myImage.jpg
and this code give me an FileNotFoundException :
this.imgInvader.Image = Image.FromFile("../Pics/invader2.jpg");
i don't understand because i see on stackoverflow that FromFile method begin at bin/Release. So a ../Pics/myImage.jpg should work no ?
Thx
Use the relative path of the image.
this.imgInvader.Image = Image.FromFile(#"bin\Pics\invader2.jpg");
Here give the path from the location where your code behind file is located. Suppose if your file is in root directory and if your images are in bin/Pics/ folder then the above code works. It automatically gets the path related to the location the program is running from.
Trying to reference image files that are outside the executable output directory is incredibly fragile. There are lots of ways it can go wrong (unfortunately, there's not enough context in your question for anyone to know exactly which of these ways is your specific problem).
If you must use files on disk to store your image resources, then they should be copied into the build output directory (i.e. "Release") and referenced there. Add the file to your Visual Studio project, select it, and in the properties window, set the "Build Action" value to "Content". If the file is in a folder under the project, then it will also be copied to a folder of the same name in the output directory.
If you do use files on disk, the other thing to make sure you do is find the executable's directory (e.g. via Path.GetDirectoryName(Assembly.GetEntryAssembly().Location)) and then combine that with your expected relative path (e.g. just the file name, or the file name under whatever folder/subdirectory you gave it in the project, if you did) using the Path.Combine() method, and then using that absolute file name as the source. Otherwise, your code can be confused by changes in the current directory made elsewhere in your program (basically, don't ever rely on the current directory…global state like that is too easy to get mixed up, once you get into the habit of using it).
For example:
string exeDirectory = Path.GetDirectoryName(Assembly.GetEntryAssembly().Location);
string imageFileName = Path.Combine(exeDirectory, "invader2.jpg");
Now, all that said, IMHO it is probably a better idea to add your images as resources in the executable itself, and then reference them from the Properties.Resources class. Then the images are always with the executable, because they are in the same file. The code is a lot easier too, because you're just referencing properties in the Resources class that return the actual Image objects you need.
As the previous comment stated, using resources outside of your exe is not advised however you can still do this by using the Path.GetDirectoryName Method.
I am left to question why your resources are based outside of your exe, why not embed it into your resources located in properties > resources.resx and simply call it with imgInvader.Image = Properties.Resources.FileNamehere; it is a lot safer than trusting the external environment.

Default path in .NET (e.g. in Picturebox.Load())

When I run SomePicturebox.Load("Foo.bmp") and there is a Foo.bmp in the application's startup folder, it will load this image. However I have a case where the image is not loaded (when the application is started by an installer, namely).
Now I am wondering: Is there a default path that is searched by the framework when the path is not fully qualified? How can I show this path at runtime (to reveal why the image is not loaded in some cases)?
I tried looking at the Picturebox.ImageLocation property but this said just "Foo.bmp" without a path.
This is related to WinForms, .NET Framework 4.
Answers in both C# and VB.NET are very welcome.
In VB.NET
Dim directory as String = My.Application.Info.DirectoryPath
In C#
string directory = AppDomain.CurrentDomain.BaseDirectory;
I tested and AlexC was correct and I have updated this answer.
The best way to get the current value for the path is with System.IO.Directory.GetCurrentDirectory().
Rather than dealing with this ambiguity, though, it is better to make sure you fully qualify the path. To get paths on a system that can change, you should use the System.Environment.GetFolderPath call. For example, if you want the user's documents folder:
var path = System.Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
If you happen to be using an open file dialog the following is another call I often find helpful:
var fullPath = System.IO.Path.GetFullPath(selectedFile);
There are quite a few other routines in the System.IO.Path namespace that can help you with making sure that your file and path names are always fully qualified. Hope these help!
Note - My answer is in C#

More Efficient way to change image in PictureBox

INTRO:
Good day dear coders! I took a look around and wasn't quite able to find answer to my simple question, tho some questions do answer my question, however they seem to be advanced for me to fathom so I'm printing here my simple situation.
QUESTION:
I want to change BackgroundImage or Image of PictureBox and thats how I am doing this:
PictureBox.Image = new Bitmap(#"C:\Users\Ailayna\documents\visual studio 2012\Projects\FormCritterTalking\FormCritterTalking\Character Pictures\CharacterNormal.png");
This picture located in one of my project folders and some how writing whole path to the picture makes no logical sense to me, since I have included all needed pictures to the project, in specific project's folder and I wonder is there a more efficient way of changing picture rather than specifying the whole path of where picture is located?
Is there a way to directly access my folder where my project pictures located using code, like for example: PictureBox.Image = FolderName.PictureName;
I would like to know how are you guys doing this in more efficient and neat way? And another thing is, do I always have to say "new Bitmap"? Can it be something else?
Is there a way to directly access my folder where my project pictures
located using code, like for example: PictureBox.Image =
FolderName.PictureName;
Yes, there is. It's called resources.
In your project select properties then chose resources. Add image.
Access it:
yourProjectName.Properties.Resources.imageName
However I'd recommend to use streams to access images. This is the right way, especially in case of bitmaps. Do not forget to dispose it afterwards. See my answer here how to do this.
I am not aware of any PictureBox control in WPF but if you are looking for the same in WPF You can do it like this in XAML:
<Image Source="/MyProject.UI.Common;component/Images/Cut.png"/>
Here your Image is located inside "Images" folder.
Disclaimer: Since you're loading a picture directly off the hard drive (and I'm assuming it's working) I'm guessing we're talking about a WinForms project.
There are a number of options you can choose from.
The simplest of which is probably getting the current application assembly folder and using that:
How do I get the path of the assembly the code is in?
var dir = AppDomain.CurrentDomain.BaseDirectory;
The images should be copied along with the executable. Then you can either use the code above to get the current directory OR you can try and rely on a relative path (from where the executable is located to the images).
Another option is to add the pictures as resources - these will be part of your application, but the procedure of reading them is a bit more complex.

Getting text file and is shiped with appliction

I have a file that I store some site links. Until now I used:
string path = Environment.CurrentDirectory + "/forumlinks.txt";
But I want to store the file in the release folder so I can change it and I know it will change permanently for the user.
So I changed to this:
string path = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) + #"/forumlinks.txt";
But I get an exception:
System.IO.FileNotFoundException.
My question: is this the right way to get the file from the release folder? Should I rethink that and store him in a different place? If so I will be glad to hear about it.
I don't see the reason why you would need to call the
System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location))
at all. This does the trick:
AppDomain.CurrentDomain.BaseDirectory
Hard coding a path to your code release folder is dangerous. What if you want to build in debug mode for some reason? What happens when you want to deploy your program?
A better choice would be to use the environment's application data folder. This will be different for each user, so it means that each user can have their own version of the file.
See this post for details of how to get the application data folder.
Well assuming the forward / is a typo.
If you've added the test file to your project, check it's properties, needs to be copy if newer / copy always to put it in bin\Debug or bin\Release, with the exe and dlls and other gubbins.
Why are you doing it this way, are you planing for something to change the file, without having to rebuild the application?
i made a mistake and found out that it was right to use this code:
string path = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location) + "\\fourmlinks.txt";
if you put the right name of the file, and still get an exception that mean that the file is not in the correct place.

Categories

Resources