How to copy an image to application folder? - c#

I already know how to browse for an image using open file dialog. So let's say we already got the path :
string imagePath = "Desktop/Images/SampleImage.jpg";
I want to copy that file, into my application folder :
string appFolderPath = "SampleApp/Images/";
How to copy the given image to the appFolderPath programmatically?
Thank you.

You could do something like this:
var path = Path.Combine(
System.AppDomain.CurrentDomain.BaseDirectory,
"Images",
fileName);
File.Copy(imagePath, path);
where fileName is the actual name of the file only (including the extension).
UPDATE: the Path.Combine method will cleanly combine strings into a well-formed path. For example, if one of the strings does have a backslash and the other doesn't it won't matter; they are combined appropriately.
The System.AppDomain.CurrentDomain.BaseDirectory, per MSDN, does the following:
Gets the base directory that the assembly resolver uses to probe for assemblies.
That's going to be the executable path you're running in; so the path in the end (and let's assume fileName is test.txt) would be:
{path_to_exe}\Images\test.txt

string path="Source imagepath";
File.Copy(System.AppDomain.CurrentDomain.BaseDirectory+"\\Images", path);
\ System.AppDomain.CurrentDomain.BaseDirectory is to provide path of the application folder

Related

Convert Relative Path to Absolute Path

I am trying to open a Help.txt file in windows Forms using a linkLabel. However unable to convert from absolute to relative path.
First, I try to get the absolute path of the exe file. Which is successful.
Second, get only directory of the exe file. Which is successful.
Third, I am trying to combine the directory with the relative path of the Help.txt file. Which is unsuccessful.
Exe file lives in -> \Project\bin\Debug folder, However the Help.txt file lives in \Project\Help folder. This is my code:-
string exeFile = (new System.Uri(Assembly.GetEntryAssembly().CodeBase)).AbsolutePath;
string Dir = Uri.UnescapeDataString(Path.GetDirectoryName(exeFile));
string path = Path.Combine(Dir, #"..\..\Help\Help.txt");
System.Diagnostics.Process.Start(path);
The result of my path is -> \Project\bin\Debug....\Help\Help.txt
You need to use Path.GetFullPath() to have the upper directory "../../" taken into account, see below :
string exeFile = new System.Uri(Assembly.GetEntryAssembly().CodeBase).AbsolutePath;
string Dir = Path.GetDirectoryName(exeFile);
string path = Path.GetFullPath(Path.Combine(Dir, #"..\..\Help\Help.txt"));
System.Diagnostics.Process.Start(path);
Per the MSDN of GetFullPath : Returns the absolute path for the specified path string.
Whereas Path.Combine Combines strings into a path.

How to locate relative file path when using GetFiles() in C#?

I've found a few related questions but they're not working that well. The image name is a modified GUID like 3c6b4a9b-8e88-4c8e-93da-258acd2c964f_0 but the extension isn't known (.jpg, .gif, ..etc). The GUID will be coming from a gridview so it's not a static string. Below is what I have but I'm having a difficult time getting the path to work correctly.
string fileName = `3c6b4a9b-8e88-4c8e-93da-258acd2c964f`;
DirectoryInfo filePath = new DirectoryInfo(#"/Images");
MessageBox.Show(filePath.ToString());
FileInfo[] fileArray = filePath.GetFiles(fileName + "_0.*");
Keep getting issues with the directory being invalid. Currently the files are stored on my c: drive.
How can I get the relative path without hardcoding it in? I was using DirectoryInfo(Server.MapPath("Images")); which worked temporarily then started giving this error System.ArgumentException: Second path fragment must not be a drive or UNC name. which seems to be from the path having the drive "C:" This doesn't seem to be a permanent solution once the site is launched though.
The actual path is C:\Website\Name\Images\3c6b4a9b-8e88-4c8e-93da-258acd2c964f_0.jpg
Thanks!
You've used filePath as the first parameter to GetFiles, just use the wildcard and invoke the overload of GetFiles with one parameter.
filePath.GetFiles("_0.*");
The problem is that you are getting DirectoryInfo for "C:\Images".
You want to use Server.MapPath to get the physical path to the folder that is in your website (which could be anywhere on any drive).
Using the ~ means to start from the root of the running website.
So this should do the trick:
string fileName = `3c6b4a9b-8e88-4c8e-93da-258acd2c964f`;
DirectoryInfo filePath = new DirectoryInfo(Server.MapPath("~/Images"));
FileInfo[] fileArray = filePath.GetFiles(fileName + "_0.*");

How to get a file full path in c# with Path.GetFullPath

I am trying to get the full path a file by its name only.
I have tried to use :
string fullPath = Path.GetFullPath("excelTest");
but it returns me an incorrect path (something with my project path).
I have read somewhere here a comment which says to do the following:
var dir = Environment.SpecialFolder.ProgramFilesX86;
var path = Path.Combine(dir.ToString(), "excelTest.csv");
but I do not know where the file is saved , therefore I do not know its environment.
can someone help me how to get the full path of a file only by its name?
The first snippet (with Path.GetFullPath) does exactly what you want. It returns something with your project path because the program EXE file is located in the project\Bin\Debug path, which is therefore the "current directory".
If you want to search for a file on a drive, you can use Directory.GetFiles, which will recursively search for a file in a directory given a name pattern.
This returns all xml-files recursively :
var allFiles = Directory.GetFiles(path, "*.xml", SearchOption.AllDirectories);
http://msdn.microsoft.com/en-us/library/ms143316%28v=vs.100%29.aspx
http://msdn.microsoft.com/en-us/library/ms143448.aspx#Y252
https://stackoverflow.com/a/9830162/2196124
I guess you're trying to find file (like in windows search), right ?
I'd look into this question - you will find all files that has that string in their filename, and from there you can return full filepath.
var fileList = new DirectoryInfo(#"c:\").GetFiles("*excelTest*", SearchOption.AllDirectories);
And then just use foreach to do you manipulations, e.g.
foreach(string file in fileList)
{
// MessageBox.Show(file);
}
What you're looking for is Directory.GetFiles(), you can read up on it here. The gist of it is, you'll pass in the file path and the file name, and you'll get a string array back. In this instance, you can assume top level with C:\. It should be noted, that if nothing is found, the string array will be empty.
You have passed a relative file name to Path.GetFullPath. Microsoft documentation states:
If path is a relative path, GetFullPath returns a fully qualified path that can be based on the current drive and current directory. The current drive and current directory can change at any time as an application executes. As a result, the path returned by this overload cannot be determined in advance.
You cannot get the same full path name from a relative path unless your current directory is the same each time you invoke the function.

Write a text file to a sub-folder

I am trying to write out a text file to: C:\Test folder\output\, but without putting C:\ in.
i.e.
This is what I have at the moment, which currently works, but has the C:\ in the beginning.
StreamWriter sw = new StreamWriter(#"C:\Test folder\output\test.txt");
I really want to write the file to the output folder, but with out having to have C:\ in the front.
I have tried the following, but my program just hangs (doesn't write the file out):
(#"\\Test folder\output\test.txt");
(#".\Test folder\output\test.txt");
("//Test folder//output//test.txt");
("./Test folder//output//test.txt");
Is there anyway I could do this?
Thanks.
Thanks for helping guys.
A colleague of mine chipped in and helped as well, but #Kami helped a lot too.
It is now working when I have:
string path = string.Concat(Environment.CurrentDirectory, #"\Output\test.txt");
As he said: "The CurrentDirectory is where the program is run from.
I understand that you would want to write data to a specified folder. The first method is to specify the folder in code or through configuration.
If you need to write to specific drive or current drive you can do the following
string driveLetter = Path.GetPathRoot(Environment.CurrentDirectory);
string path = diveLetter + #"Test folder\output\test.txt";
StreamWriter sw = new StreamWriter(path);
If the directory needs to be relative to the current application directory, then user AppDomain.CurrentDomain.BaseDirectory to get the current directory and use ../ combination to navigate to the required folder.
You can use System.IO.Path.GetDirectoryName to get the directory of your running application and then you can add to this the rest of the path..
I don't get clearly what you want from this question , hope this get it..
A common technique is to make the directory relative to your exe's runtime directory, e.g., a sub-directory, like this:
string exeRuntimeDirectory =
System.IO.Path.GetDirectoryName(
System.Reflection.Assembly.GetExecutingAssembly().Location);
string subDirectory =
System.IO.Path.Combine(exeRuntimeDirectory, "Output");
if (!System.IO.Directory.Exists(subDirectory))
{
// Output directory does not exist, so create it.
System.IO.Directory.CreateDirectory(subDirectory);
}
This means wherever the exe is installed to, it will create an "Output" sub-directory, which it can then write files to.
It also has the advantage of keeping the exe and its output files together in one location, and not scattered all over the place.

Get File From an Assembly

I want to read a file path from the following structure
The Structure is like : AssemblyName -> MyFiles (Folder) -> Text.txt
Here I want to get the path of the Text.txt. Please help
I think what you're looking for is a file embedded in the assembly. Check out this question. The first answer explains how to set up an embedded file, as well as how to get it from code.
You can do
string assemblyPath = Assembly.GetExecutingAssembly().Location;
string assemblyDirectory = Path.GetDirectoryName(assemblyPath);
string textPath = Path.Combine(assemblyDirectory, "MyFiles", "Test.txt");
string text = File.ReadAllText(textPath);
...just to split it up some...but you could write it all in one line needless to say...
alternatively, if your Environment.CurrentDirectory is already set to the directory of your executing assembly's location, you could just do
File.ReadAllText(Path.Combine("MyFiles", "Text.txt"));
Jeff has covered how you get the path, wrt your comment on his answer is the file you want to open actually included in your project output?
Under the properties pane for the relevant file look at the Copy to Output Directory option - it generally defaults to Do not copy. You will want to set it to Copy Always or Copy if Newer if you want to include a file in the output directory with your compiled program.
As a general note you should always wrap any IO in an appropriate try catch block or use the static File.Exists(path) method to check whether a file exists

Categories

Resources