How to get image files in c# using relative path? - c#

I've checked this thread How to get files in a relative path in C#, the directory is in IDE, which is not correct for me. I have a website application, needs to get image files from the same level folder img. I can use following code to get them:
DirectoryInfo path=new DirectoryInfo(#"c:\WebsiteSolution\wwwroot\Chat\img");
FileInfo[] images = path.GetFiles("*");
But I want to use something like .\img to replace the parameter in the first line code, is that possible?

Call the Server.MapPath utility to get the relative path.
DirectoryInfo path = Server.MapPath("~\Chat\img");

For ASP.Net use MapPath - http://msdn.microsoft.com/en-us/library/system.web.httpserverutility.mappath.aspx.
Also if you just need to construct path for rendering a page just /Chat/img/My.gif is enough.

You need to find an anchor - something like Application.ExecutablePath - and then use that anchor with Path.Combine() to reach your image directory.
If your Application.ExecutablePath were: #"c:\WebSiteSolution\wwwroot\chat\code", then you could use string imgPath = Path.Combine(Application.ExecutablePath, #"..\img");
If you have a hard time finding a good anchor, there's a bunch to consider. You can get the path of the executing assembly via Assembly.GetExecutingAssembly().Location

Related

Make folder in .special folder hidden C#

i know im doing something small wrong im just braindead right now. The path is the problem, i tried to use path.combine and also put system.IO in front of it but nothing worked.
string path = (Environment.SpecialFolder.ApplicationData + #"\MSPhone").ToString();
File.SetAttributes(path, FileAttributes.Hidden);
you need to use Environment.GetFolderPath along with your SpecialFolder. Environment.SpecialFolder.ApplicationData is just an enum value, not representative of the path without acting on it:
Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData),
"MSPhone");
this gives me "C:\Users\jonesopolis\AppData\Roaming\MSPhone"
and of course, always use Path.Combine rather than building the path yourself.

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

Open a text file with WPF

There is a text file that I have created in my project root folder. Now, I am trying to use Process.Start() method to externally launch that text file.
The problem I have got here is that the file path is incorrect and Process.Start() can't find this text file. My code is as follows:
Process.Start("Textfile.txt");
So how should I correctly reference to that text file? Can I use the relative path instead of the absolute path? Thanks.
Edit:
If I change above code to this, would it work?
string path = Assembly.GetExecutingAssembly().Location;
Process.Start(path + "/ReadMe.txt");
Windows needs to know where to find the file, so you need somehow specify that:
Either using absolute path:
Process.Start("C:\\1.txt");
Or set current directory:
Environment.CurrentDirectory = "C:\\";
Process.Start("1.txt");
Normally CurrentDirectory is set to the location of the executable.
[Edit]
If the file is in the same directory where executable is you can use the code like this:
var directory = Path.GetDirectoryName(Assembly.GetEntryAssembly().Location);
var file = Path.Combine(directory, "1.txt");
Process.Start(file);
The way you are doing this is fine. This will find the text file that is in the same directory as your exe and it will open it with the default application (probably notepad.exe). Here are more examples of how to do this:
http://www.dotnetperls.com/process-start
However, if you want to put a path in, you have to use the full path. You can build the full path while only caring about the relative path using the method listed in this post:
http://social.msdn.microsoft.com/Forums/en-US/vbgeneral/thread/e763ae8c-1284-43fe-9e55-4b36f8780f1c
It would look something like this:
string pathPrefix;
if(System.Diagnostics.Debugger.IsAttached())
{
pathPrefix = System.IO.Path.GetFullPath(Application.StartupPath + "\..\..\resources\");
}
else
{
pathPrefix = Application.StartupPath + "\resources\";
}
Process.Start(pathPrefix + "Textfile.txt");
This is for opening a file in a folder you add to your project called resources. If you want it in your project root, just drop off the resources folder in the above two strings and you will be good to go.
You'll need to know the current directory if you want to use a relative path.
System.Envrionment.CurrentDirectory
You could append that to your path with Path
System.IO.Path.Combine(System.Envrionment.CurrentDirectory, "Textfile.txt")
Try using Application.StartupPath path as default path may point to current directory.
This scenario has been explained on following links..
Environment.CurrentDirectory in C#.NET
http://start-coding.blogspot.com/2008/12/applicationstartuppath.html
On a windows box:
Start notepad with the file's location immediately following it. WIN
process.start("notepad C:\Full\Directory\To\File\FileName.txt");

How can I load an image from a specific directory in C#?

I would like to load an image from a directory "../MyAppFolder/Logos".
My code:
Bitmap bmp = new Bitmap(#"/Logos/bitmap.bmp");
pictureBox1.Image = bmp;
This code doesn't work. When I use (#"/Bitmapx.bmp") it works, but when I want to load an image from a deeper directory I get an error message.
What am I doing wrong?
The leading slash targets the current drive root. Use the realative path...
Bitmap bmp = new Bitmap(#"Logos/bitmap.bmp");
..Or one of the many Path. methods to resolve the full path that you want.
and yes I know my example above targets the current working path... that would be why I added the above comment. And for the pointless downvoter you might like to learn that current versions of Windows don't care which slash you use.
Try this:
string myLogo = System.IO.Path.Combine(Application.StartupPath, #"Logos\bitmap.bmp");
Bitmap bmp = new Bitmap(myLogo);
pictureBox1.Image = bmp;
And make sure your Logos folder is in your application root folder.
The first character of your path is / which makes this path relative to the root level of the drive on which the current working directory lives. But you probably want a relative path so just remove the initial /.
What's more, relative paths are relative to the working directory. But the working directory is not necessarily the application directory. For example, if you navigate in a file dialog that can change your working directory.
If I were you I would probably pre-pend the path with the app directory and make it a fully-specified absolute path, exactly as HABJAN suggests.

Getting the physical path

I have to fetch all the files from a folder and i am using the function GetFiles() like
string[] dirImages = Directory.GetFiles(strPathYearImages + intYear , "*.png");
where strPathYearImages="Images\Holiday\2010\"
but when i write the whole path like
string[] dirImages = Directory.GetFiles(#"E:\IWP\Images\Holiday\"+ intYear , "*.png");
i get the required result.
How to solve this problem? I dont want to use the whole path.
Help me out.
Regards,
Jigar <3
The documentation for GetFiles() says:
The path parameter is permitted to
specify relative or absolute path
information. Relative path information
is interpreted as relative to the
current working directory
So you would want to make sure the current working directory is set correctly before trying to use the relative paths (eg to E:\IWP):
GetCurrentDirectory
SetCurrentDirectory
Use Application.StartupPath to get the location where the executable is running. From there you need to know where the images directory is relative to that directory. The only other option is the absolute path. How else would it know where to look?
You can also try using System.IO.Path methods to help - especially for combining path strings, plus it also gives you the location of special folders like My Documents, AppData, and the desktop.
Maybe it's because you are running it from VS inside. Your executable is in ProjectName\bin\Debug, therefore it looks for ProjectName\bin\Debug\Images, which obviously does not exists.
The problem is the first snippet tries to get the images under current path. So you could tell the images path relative to your current path.
Hey all, i got the answer to my question.
I just had to write
string[] dirImages = HttpContext.Current.Server.MapPath(strPathImages + intYear , "*.png");
Hope that it is helpful to all...

Categories