Get Files In Project Folder - c#

I have an Images folder in my visual studio project.
How can I reference the images within this folder so I can use the .exe file on other computers?
Ultimately I am trying to do the following (obviously replacing "Images/image1.jpg" with imageFile).
foreach (string imageFile in imageFolder)
{
ImageSource imageSource = new BitmapImage(new Uri("Images/image1.jpg", UriKind.Relative));
}
Using something like:
Directory.GetParent(Directory.GetCurrentDirectory()).Parent.FullName
doesn't work because the .exe could be running in any location.

If you don't need to add or remove such images during the installation of the application on the user's computer, add the images to the resources by dragging them to the Resources tab in the project properties and reference them using Properties.Resources within your code.

If you're using copying the image folder to the output of your application and taking the folder with you to the new computers you could use
var path = Path.GetDirectoryName(Assembly.GetExecutingAssembly().CodeBase)
If you don't have lots of large images, why not include them as embedded resources. http://support.microsoft.com/kb/319292

Keep images (and other resources) together with exe-file (either in the same folder, which is simplest, or use directory structure).
To example:
\Bin
my.exe
my.pdb
\Help
my.html
\Resources
1.jpg
2.jpg
Then you can so something like
private static string PathRoot { get { return Path.GetDirectoryName(Path.GetDirectoryName(Application.ExecutablePath)); } }
public static string PathResources { get { return Path.Combine(PathRoot, "Resources"); } }

Related

How to get the URI link to WAV file after compilation?

Currently experimenting with WPF here. I'm trying to use URI files to stock music in a table.
It currently works, but as expected only on my computer as it is an absolute path:
private readonly Uri[] SoundsTable = new Uri[] { new Uri(#"C:\Users\damie\Desktop\repos2\Tetrics\Tetrics\Assets\music_theme.wav"), new Uri(#"C:\Users\damie\Desktop\repos2\Tetrics\Tetrics\Assets\line_clear.wav"), };
I'm running into a problem where I can't access my music files after compiling. I can't use a relative path or determine it getting the Path.CurrentDirectory() (because my asset folder isn't generated in the compiled project).
I don't have this problem for images that can be stocked in my DLL:
`private readonly ImageSource[] tileImages = new ImageSource[] {
new BitmapImage(new Uri("Assets/TileEmpty.png", UriKind.Relative)),
new BitmapImage(new Uri("Assets/TileCyan.png", UriKind.Relative)),
new BitmapImage(new Uri("Assets/TileBlue.png", UriKind.Relative)),
new BitmapImage(new Uri("Assets/TileOrange.png", UriKind.Relative)),
new BitmapImage(new Uri("Assets/TileYellow.png", UriKind.Relative)),
new BitmapImage(new Uri("Assets/TileGreen.png", UriKind.Relative)),
new BitmapImage(new Uri("Assets/TilePurple.png", UriKind.Relative)),
new BitmapImage(new Uri("Assets/TileRed.png", UriKind.Relative))
};`
Does anyone have any idea of what to do here ?
I have tried to change my IDE properties for the music files, like build action and copy to output folder.
I think my answer could be here but none of what I tried worked.
Thanks a lot to anyone who responds !
If you looked inside your bin, found the compiled exe and there's no Assets folder there, then you probably haven't set the right properties on your files.
You need an Assets folder in your project.
That must have some files in it.
Their properties must be set to Build action "Content" and Copy to output directory "Copy if newer".
If you do that then you will have an assets folder with files in it within your bin after you compile.
You can then reference those files using an absolute url which would be:
Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory, "Assets", yourfilename)
I assume the mention of png files is just to show us something else which is working for you.
However.
There is also a pack notation in wpf which you should take a look at if you are going to reference files in xaml.
https://learn.microsoft.com/en-us/dotnet/desktop/wpf/app-development/pack-uris-in-wpf?view=netframeworkdesktop-4.8
Relative paths are evaluated relative to the current directory. In turn, the current directory may be different depending on how exactly you launch your application. It can change during the course of an application session.
In some cases, this is provided by the logic of the application itself. For example, selecting the current folder and showing the files in it. But this is clearly not your case.
You need to get the full path to the files in the application folder (conditionally the folder with the exe file) using the relative path. The best way to do this is an explicit conversion.
Here is an example of such a transformation.
public static string RelativeToAbsoluteAppPath(string relative)
=> System.OI.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, relative);
public static string AbsoluteAppUri(string relative)
=> new Uri(RelativeToAbsoluteAppPath(string relative), UriKind.Absolute);
... = new BitmapImage(AbsoluteAppUri("Assets\music_theme.wav"));
P.S. Of course, as #Andy wrote, you must also make sure that the necessary files really exist at the specified paths.

how to choose and load a file with any extension at runtime in unity

I am creating a game in unity that requires some files to be stored in the database. To begin with , when the game is running , the user clicks on a button , it opens the file chooser , user chooses and it stored in db. How can I do this in unity during run time ? Any help is appreciated. Thanks
Ps : files could be .fbx, .obj or even .txt , .lbr etc..
Using the bearbone System.IO wont work for Unity simply because once compiled the game wont retain its editor way of having actual folders it will all be compiled into one file.
It will work in the editor though in play mode you will be able to use it and the only way of it to be useful would be to make tools for the editor, but for this particular case you should consider AssetsBundle more on that here
You need to make and fill your own directory browser.
For this you can use System.IO.
You need to follow 4 steps:
protected string[] m_files;
protected string[] m_folders;
1.- Set your path:
CurrentDirectory = path;
2.- Read files in path:
m_files = Directory.GetFiles(CurrentDirectory, "*.myExtension");
3.- Read folders in path:
m_folders = Directory.GetDirectories(CurrentDirectory);
4.- Make your browser adding file & folder icons with your customs gameobjects, extracting filenames and foldernames from m_files and m_folders arrays.
private string GetFolderName(string file)
{
DirectoryInfo info = new DirectoryInfo(file);
string shortname = info.Name;
return shortname;
}
private string GetFileName(string file)
{
string shortname = Path.GetFileNameWithoutExtension(file);
return shortname;
}
To navigate to another folder you need to set an action to a directory icon elements and change path and read again files and directories.

Add Images to windows form so they work after publish

I am currently setting my images in my windows form like this:
pictureBox1.Image = Image.FromFile("C:\\Users\\User\\Documents\\Visual Studio 2013\\Projects\\WindowsFormsApplication1\\WindowsFormsApplication1\\Krum\\11.jpg");
But this will not work after I publish the product and load it from another computer at another location.
How do I add images to my project so that they will work after I publish and send it to another computer? What path do I use and where do I need to add them?
UPDATE:
Trying to find the path to my file after adding it to properties is not working very well. In my prperties the file looks like this:
internal static System.Drawing.Bitmap one {
get {
object obj = ResourceManager.GetObject("one", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
And then I try to use it like this:
System.Reflection.Assembly thisExe;
thisExe = System.Reflection.Assembly.GetExecutingAssembly();
System.IO.Stream file =
thisExe.GetManifestResourceStream("WindowsFormsApplication1.Properties.Resources.one");
this.pictureBox1.Image = Image.FromStream(file);
Add the image file to the project, and set the Build Action property to Embedded Resource in Solution Explorer and then use something like:
System.Reflection.Assembly thisExe;
thisExe = System.Reflection.Assembly.GetExecutingAssembly();
System.IO.Stream file =
thisExe.GetManifestResourceStream("AssemblyName.ImageFile.jpg");
this.pictureBox1.Image = Image.FromStream(file);
reference: http://msdn.microsoft.com/en-us/library/aa287676(v=vs.71).aspx
If you do not want to embed the images in the assembly file, you could always add them to your solution, set the property "Copy to Output Directory" to "Always", then use the following code to acces relative paths:
var directory = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
var filename = Path.Combine(directory, "Images", "Image1.png");
Additionally, if you are using a setup project, also include the folder/files to install along with the assembly.

Having Trouble Accessing an Embedded Resource [duplicate]

I have a game application in Visual Studio 2012 C#. I have all the .png images I am using in the Resources file of the project.
Have you any idea why I can access all the files but one by using Properties.Resources?
I checked the full filePath and it's set to the resources folder. And it's added in the program as I did Add -> Existing Item and added the image.
It looks just like the other images. I have no idea why it's not loading. I need this since I need to send a .exe by email to my lecturer and without this image the project is nothing!
I added this in the resource file
internal static System.Drawing.Bitmap grid_fw {
get
{
object obj = ResourceManager.GetObject("grid.fw", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
and although now grid is available, it is returning null :/
Found from: Properties.Resources the icon name does not appear in the intellisense
You also need to add the icon to the Resources.resx file. Open it in
Visual Studio and drag your icon into the Icons menu of the resx and
it will become available.
Also, see Adding and Editing Resources (Visual C#)
You can get a reference to the image the following way:
Image myImage = Resources.yourImage;
If you want to make a copy of the image, you'll need to do the following:
Bitmap bmp = new Bitmap(Resources.yourImage);
Don't forget to dispose of bmp when you're done with it. If you don't know the name of the resource image at compile-time, you can use a resource manager:
ResourceManager rm = Resources.ResourceManager;
Bitmap yourImage = (Bitmap)rm.GetObject("yourImage");
The benefit of the ResourceManager is that you can use it where Resources.myImage would normally be out of scope, or where you want to dynamically access resources. Additionally, this works for sounds, config files, etc.

Accessing files from the project folder of a WP app

I'm new to Windows Phone development and I'm trying to do a simple training app.
I want my app to load some audio files that I've put into a folder inside the project.
Here's a short snippet:
private void LoadSound(String SoundFilePath, out SoundEffect Sound)
{
// For error checking, assume we'll fail to load the file.
Sound = null;
try
{
// Holds informations about a file stream.
StreamResourceInfo SoundFileInfo = Application.GetResourceStream(new Uri(SoundFilePath, UriKind.Relative));
My folder structure is something like
- Project
- Kits
- TestKit_128
- Bass_126.wav
and calling
Button.setSound("Kits\\TestKit_128\\bass_126.wav");
throws a System.NullReferenceException because the path is not found when the URI is created. (At least I think so!)
What should I do?
Is there any way to load files from a folder in the project or to copy them into the IsolatedStorage when I run the app for the first time?
Thanks
EDIT:
I've just opened the XAP file with WinRar and there's no "Kits" folder so I guess that my problem is how to make it add the folder to the XAP file.
I think you have to add the folder and the file to your project (i assume you are using Visual Studio). Try rightclick on your solution and add an existing object (in this case your wav file).
Did you set the build action of the wav file to "Content"? Right click on the WAV file --> properties --> build action == content.
Try this:
Uri uri = new Uri("Kits/TestKit_128/bass_126.wav", UriKind.Relative);//Above the Kits folder only the project itself.
StreamResourceInfo sr = Application.GetResourceStream(uri);
try
{
using (Stream stream = sr.Stream)
{
//working here with your data image or wav or whatever you want from URI
}
}
catch (Exception)
{
}
This is for resource inside project and working good for me. Also prevoius note about "Content" is right, it wouldn't work without it. I think the problem is double-slashes in address.

Categories

Resources