Simply get files from internal project folder [duplicate] - c#

This question already exists:
Closed 10 years ago.
Possible Duplicate:
how to populate a listbox with files in the project of my windows phone 7 application
I'm a newbie on C# and this is annoying me a lot.
My application load a set of images from a folder that I simply created on the Solution Explorer called Images. I can see these images if I use it hardcoded with URIs and stuff, but what I want to do is to take these images names dinamycally and then load it. I have seen some questions like it but couldnt solve my problem. I'm trying like this:
DirectoryInfo directoryInfo = new DirectoryInfo(#"/Images");
foreach (FileInfo file in directoryInfo.GetFiles()) {
photos.Add(new Photo() { FileName = file.FullName, PhotoSource = GetImageSource("Images/" + file.FullName) });
}
The directoryInfo is always set as null. My project hierarchy as shown in Solution Explorer is like:
Project
Main.xaml
Maim.xaml.cs
Images
1.jpg
2.jpg
...
Thanks in any help.

From MSDN:
For a Windows Phone application, all I/O operations are restricted to
isolated storage and do not have direct access to the underlying
operating system file system or to the isolated storage of other
applications.
So you can't access your Images folder in the manner you'd like.
Since you can't add images dynamically to your XAP anyway, the images available will be constant. It appears you will just have to add the URIs manually:
BitmapImage myImage = new BitmapImage(new Uri("Images/myImage.png", UriKind.Relative));
If you've got different images for different locales, you could include the image name/path in a resources file and then create them from there.
Alternatively if you have a set of default images and will then have some user-added ones, and you'd like to iterate over all of those, you could write your defaults from your Images folder into IsolatedStorage at first start-up. See here for details on using IsolatedStorage. You can iterate over directories and files within the apps IsolatedStorageFile (see the methods available).

Maybe you want to use
string path = Path.Combine(Environment.CurrentDirectory, "Images");
foreach (string file in Directory.GetFiles(path)
{
photos.Add(new Photo {FileName = file, PhotoSource = GetImageSource(Path.Combine(path, Path.GetFileNameWithoutExtension(file))});
}
which returns a List of the Contents of the Folder.
Path.Combine combines single strings to a full Path (So you don't need to worry about the Backslahes.
The Path Namespace is pretty underrated, i'd suggest you to take a close look to it since it will save you much time.

Related

How get file from a directory using relative path?

I am pretty new in C# and I am finding some difficulties trying to retrieve a jpg file that is into a directory of my project.
I have the following situation:
I have a Solution that is named MySolution, inside this solution there are some projects including a project named PdfReport. Inside this project there is a folder named Shared and inside this folder there is an header.jpg file.
Now if I want to obtain the list of all files that are inside the Shared directory (that as explained is a directory inside my project) I can do something like this:
string[] filePaths = Directory.GetFiles(#"C:\Develop\EarlyWarning\public\Implementazione\Ver2\PdfReport\Shared\");
and this work fine but I don't want use absolute path but I'd rather use a relative path relative to the PdfReport project.
I am searching a solution to do that but, untill now, I can't found it. Can you help me to do that?
Provided your application's Executable Path is "C:\Develop\EarlyWarning\public\Implementazione\Ver2", you can access the PdfReport\Shared folder as
string exePath = System.IO.Path.GetDirectoryName(Application.ExecutablePath);
string sharedPath = Path.Combine(exePath, "PdfReport\\Shared\\");
string[] filePaths = Directory.GetFiles(sharedPath);
Try to get the current folder by using this
Server.MapPath(".");
In a non ASP.NET application but WinForms or Console or WPF application you should use
AppDomain.CurrentDomain.BaseDirectory
If you want root relative, you can do this (assuming C:\Develop\EarlyWarning is site root)
string[] filePaths = Directory.GetFiles(Server.MapPath("~/public/Implementazione/Ver2/PdfReport/Shared"));
Or if you want plain relative,
//assuming you're in the public folder
string[] filePathes = Directory.GetFiles(Server.MapPath("/Implementazione/Ver2/PdfReport/Shared"));
Root relative is usually best in my experience, in case you move the code around.
You can right click on your file header.jpg, choose Properties, and select for example the option Copy always on the property "Copy to Output Directory".
Then a method like this, in any class that belongs to project PdfReport:
public string[] ReadFiles()
{
return Directory.GetFiles("Shared");
}
will work well.
Alternatively, if you have files that never change at runtime and you want to have access to them inside the assembly you also can embed: http://support.microsoft.com/kb/319292/en-us

How to get all files list from a relative URI in XAML application?

How to get all files from a folder in XAML application using relative path?
I am playing with a Kinect application built in WPF. All images used in the application are in
[project dir]\Images\ and all backgrounds are in
[project dir]\Images\Backgrounds\.
I want to get list of all the images from Backgrounds directory using relative path. I have tried
DirectoryInfo(#"\Images\Backgrounds\").GetFiles();
but it says that Backgrounds directory must exist in [full path+project dir]\debug\bin\
Selecting each image manually works fine
Uri uri = new Uri(#"Images\Backgrounds\Background1.png", UriKind.Relative);
ImageSource imgsource = new BitmapImage(uri);
this.Backdrop.Source = imgsource;
It works for a single file because you specify URI to resource embedded in the assembly and not some folder on your drive, whilst GetFiles() will work only on a specific physical folder. So either you need to copy all your images instead of embedding them or use the code below and resourceNames should give you names of all resources that you can reference by URI in your project:
List<string> resourceNames = new List<string>();
var assembly = Assembly.GetExecutingAssembly();
var rm = new ResourceManager(assembly.GetName().Name + ".g", assembly);
try
{
var list = rm.GetResourceSet(CultureInfo.CurrentCulture, true, true);
foreach (DictionaryEntry item in list)
resourceNames.Add((string)item.Key);
}
finally
{
rm.ReleaseAllResources();
}
if you need then at this point each item.Value contains UnmanagedMemoryStream for each resource.
I would reply to your post instead of posting a solution, but I'm new to this site and dont have that privledge yet.... Hey! Just trying to help.
Anyway, I've had a problem similar to this before concerning DirectoryInfo. Can't remember exactly how I solved it, but I remember the backslashes being tricky. Have you checked out the MSDN site? It seems like it can't find your directory so its looking for it in debug by default. MSDN says the format should be "MyDir\MySubdir" in C#.

Converting absolute path to relative path C# [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Getting path relative to the current working directory?
I have code in C# that includes some images from an absolute path to a relative so the image can be found no matter where the application fold is located.
For example the path in my code (and in my laptop for the image) is
C:/something/res/images/image1.jpeg
and I want the path in my code to be
..../images/image1.jpeg
So it can run wherever the folder is put, whatever the name of the C: partition is etc.
I want to have a path in my code which is independant of the application folder location or if it is in another partition, as long as it is in the same folder as the the rest of the solution.
I have this code:
try
{
File.Delete("C:/JPD/SCRAT/Desktop/Project/Resources/images/image1.jpeg");
}
catch (Exception)
{
MessageBox.Show("File not found:C:/Users/JPD/Desktop/Project/images/image1.jpeg");
}
This code only runs if the file and folder are in that certain path, (which is also the location of the code) I wish for that path to be relative so wherever I put the whole folder (code, files etc) the program will still work as long as the code (which is under project folder) is at the same location with the folder images... what should I do?
Relative paths are based from the binary file from which your application is running. By default, your binary files will be outputted in the [directory of your .csproj]/bin/debug. So let's say you wanted to create your images folder at the same level as your .csproj. Then you could access your images using the relative path "../../images/someImage.jpg".
To get a better feel for this, try out the following as a test:
1) create a new visual studio sample project,
2) create an images folder at the same level as the .csproj
3) put some files in the images folder
4) put this sample code in your main method -
static void Main(string[] args)
{
Console.WriteLine(Directory.GetCurrentDirectory());
foreach (string s in Directory.EnumerateFiles("../../images/"))
{
Console.WriteLine(s);
}
Console.ReadLine(); // Just to keep the console from disappearing.
}
You should see the relative paths of all the files you placed in step (3).
see: Getting path relative to the current working directory?
Uri uri1 = new Uri(#"c:\foo\bar\blop\blap");
Uri uri2 = new Uri(#"c:\foo\bar\");
string relativePath = uri2.MakeRelativeUri(uri1).ToString();
Depending on the set up of your program, you might be able to simply use a relative path by skipping a part of the full path string. It's not braggable, so J. Skit might be up my shiny for it but I'm getting the impression that you simply want to make it work. Beauty being a later concern.
String absolutePath = #"c:\beep\boop\HereWeStart\hopp.gif";
String relativePath = absolutePath.Substring(13);
You could then, if you need/wish, exchange the number 13 (which is an ugly and undesirable approach, still working, though) for a dynamically computed one. For instance (assuming that the directory "HereWeStart", where your relative path is starting, is the first occurrence of that string in absolutePath) you could go as follows.
String absolutePath = #"c:\beep\boop\HereWeStart\hopp.gif";
int relativePathStartIndex = absolutePath.IndexOf("HereWeStart");
String relativePath = absolutePath.Substring(relativePathStartIndex);
Also, your question begs an other question. I'd like to know how you're obtaining the absolute path. Perhaps there's an even more clever way to avoid the hustle all together?
EDIT
You could also try the following approach. Forget the Directory class giving you an absolute path. Go for the relative path straight off. I'm assuming that all the files you're attempting to remove are in the same directory. If not, you'll need to add some more lines but we'll cross that bridge when we get there.
Don't forget to mark an answer as green-checked (or explain what's missing or improvable still).
String
deletableTarget = #"\images\image1.jpeg",
hereWeAre = Environment.CurrentDirectory;
MessageBox.Show("The taget path is:\n" + hereWeAre + deletableTarget);
try
{ File.Delete(hereWeAre + deletableTarget); }
catch (Exception exception)
{ MessageBox.Show(exception.Message); }
Also, please note that I took the liberty of changing your exception handling. While yours is working, it's a better style to rely on the built-in messaging system. That way you'll get more professionally looking error messages. Not that we ever get any errors at run-time, right? ;)

Creating files programmatically and getting the file names from WP7 isolated storage

I am building an app which requires saving a form whenever user enter the details. I want each form to be stored in separate .dat file. Using GUID as file names, I am able to store the data in separate files now. But I am not able to retrieve all the filenames and bind it to a listbox of hyperlinkbutton, on click of which will show all the data stored in the particular file. Please help!
Maybe you want to have a look at:
http://msdn.microsoft.com/en-us/library/cc190395(v=vs.95).aspx
"GetFileNames" is a method of "IsolatedStorageFile" which shows all the files in the directory it is pointing to.
In this question you can get an example:
How to read names of files stored in IsolatedStorage
Try using the GetFilesNames method of your IsolatedStorageFile. Use a wildcard (*.dat) to retrieve a list of your files.
For example:
using (var store = IsolatedStorageFile.GetUserStoreForApplication())
{
string pattern = "*.dat";
string[] files = store.GetFileNames(pattern);
}

How do you programatically find Vista's "Saved Games" folder?

I am using XNA and I want to save files to Vista's "Saved Games" folder.
I can get similar special folders like My Documents with Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) but I cannot find an equivalent for the Saved Games folder. How do I get to this folder?
http://msdn.microsoft.com/en-us/library/bb200105.aspx#ID2EWD
Looks like you'll need to use Microsoft.Xna.Framework.Storage and the StorageLocation class to do what you need to.
Currently, the title location on a PC
is the folder where the executable
resides when it is run. Use the
TitleLocation property to access the
path.
User storage is in the My Documents
folder of the user who is currently
logged in, in the SavedGames folder. A
subfolder is created for each game
according to the titleName passed to
the OpenContainer method. When no
PlayerIndex is specified, content is
saved in the AllPlayers folder. When a
PlayerIndex is specified, the content
is saved in the Player1, Player2,
Player3, or Player4 folder, depending
on which PlayerIndex was passed to
BeginShowStorageDeviceSelector.
There is no special folder const for it so just use System Variables. According to this Wikipedia article Special Folders, the saved games folder is just:
Saved Games %USERPROFILE%\saved games Vista
So the code would be:
string sgPath = System.IO.Path.Combine(Environment.GetEnvironmentVariable("USERPROFILE"), "saved games"));
...
EDIT: If, as per the comments, localization is an issue and as per your question you still want access to the Saved Games folder directly rather than using the API, then the following may be helpful.
Using RedGate reflector we can see that GetFolderPath is implemented as follows:
public static string GetFolderPath(SpecialFolder folder)
{
if (!Enum.IsDefined(typeof(SpecialFolder), folder))
{
throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, GetResourceString("Arg_EnumIllegalVal"), new object[] { (int) folder }));
}
StringBuilder lpszPath = new StringBuilder(260);
Win32Native.SHGetFolderPath(IntPtr.Zero, (int) folder, IntPtr.Zero, 0, lpszPath);
string path = lpszPath.ToString();
new FileIOPermission(FileIOPermissionAccess.PathDiscovery, path).Demand();
return path;
}
So maybe you think all i need is to create my own version of this method and pass it the folder id for Saved Games. That wont work. Those folder ids pre-Vista were actually CSIDLs. A list of them can be found here. Note the Note: however.
In releasing Vista, Microsoft replaced CLSIDLs with KNOWNFOLDERIDs. A list of KNOWNFOLDERIDs can be found here. And the Saved Games KNOWNFOLDERID is FOLDERID_SavedGames.
But you don't just pass the new const to the old, CLSIDL based, SHGetFolderPath Win32 function. As per this article, Known Folders, and as you might expect, there is a new function called SHGetKnownFolderPath to which you pass the new FOLDERID_SavedGames constant and that will return the path to the Saved Games folder in a localized form.
The easiest way I found to get the Saved Games path was to read the Registry value likes this:
var defaultPath = Path.Combine(Environment.GetEnvironmentVariable("USERPROFILE"), "Saved Games");
var regKey = "HKEY_CURRENT_USER\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders";
var regKeyValue = "{4C5C32FF-BB9D-43b0-B5B4-2D72E54EAAA4}";
var regValue = (string) Registry.GetValue(regKey, regKeyValue, defaultPath);
I changed the location of my Saved Games via the Shell multiple times and the value of this key changed each time. I use the USERPROFILE/Saved Games as a default because I think that will work for the default circumstance where someone has never changed the location.

Categories