I want to find image path but I didn't.
my image path : C:\Works\Web5.1.0\Src\Works.WebNext\Password\assets\img
my image name : reset_password.jpg
I tried this : string path2 = Path.GetFullPath("reset_password.jpg"); but it's wrong path (output: C:\Windows\System32\inetsrv)
and tried this :
string path = Path.GetDirectoryName(Assembly.GetExecutingAssembly().CodeBase);
string a = Path.Combine(path, "reset_password.jpg");
output : (C:\Works\Web5.1.0\Src\Works.WebNext\bin )
I think, output should be like this : C:\Works\Web5.1.0\Src\Works.WebNext\Password\assets\img
one more thing : image path may not be same another computer so I think give a specific path is not right (for example : C:\Works\Web5.1.0\Src\Works.WebNext\Password\assets\img )
X computer : C:\Works\Web5.1.0\Src\Works.WebNext\Password\assets\img
Y computer : C:\Works\Web\Src\Works.WebNext\Password\assets\img
By the way, I am writing with c#.
How can I do ?
Any ideas please.
I'm not sure I've understood the issue but an idea of how to find the same file on many systems is:
AppDomain.CurrentDomain.BaseDirectory
This will give you the location of the folder that your running executable is in. The output is in the format of
"C:\Folder\Folder\WindowsFormsApplication1\WindowsFormsApplication1\bin\Debug\".
So, you can put the image in the same folder as the .exe, add "imagefilename.type" and you should find it.
Please clarify if this doesn't answer your question.
Following code will give you your desired output
string folderPath = #"C:\Works\Web5.1.0\Src\Works.WebNext\Password\assets\img";
string imgFilePath = Path.Combine(folderPath, "reset_password.jpg")
Assembly.GetExecutingAssembly() gives the path of the current working directory i.e. the path from where your executables are being run (in your case its 'bin' folder)
Try this for Web Applications.
string imagePath = "/Password/"; /* Your Image folder */
string path = Server.MapPath(#"ImagePath" + imagePath);
In Windows Application:
try
{
System.IO.DirectoryInfo directory = new DirectoryInfo(#"Your local Image directory inside bin/debug");
FileInfo result = null;
var list = directory.GetFiles(); // Stackoverflow Exception occurs here
if (list.Count() > 0)
{
result = list.OrderByDescending(f => f.LastWriteTime).First();
}
return result;
}
catch (Exception ex)
{
throw ex;
}
Related
I am having a problem with coding my save-directory. I want it to create a folder called "Ausgabe" (Output) on the current users Desktop, but I do not know how to check if it already exists and if it doesn't then create it.
This is my current code for that part so far:
public partial class Form1 : Form
{
string path = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
// need some code here
}
What do I add in order to make it do what I want it to do?
You can check if a directory exists using
Directory.Exists(pathToDirectory)
and create a directory using
Directory.CreateDirectory(pathToDirectory)
EDIT In response to your comment:
string directoryPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "Ausgabe")
should give you the path to a folder named 'Ausgabe' in the users Desktop-folder.
Just use Directory.CreateDirectory. If the directory exists the method will not create it (in other words it contains a call to Directory.Exists internally)
public partial class Form1 : Form
{
string path = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
public Form1()
{
string myFolder = Path.Combine(path, "Ausgabe");
Directory.CreateDirectory(myFolder);
}
To use this method you need to add a using System.IO to the top of your Form1.cs file.
I wish also to say that the Desktop is not the most appropriate place to create a directory for your application. There is a proper place provided by the System and it is under the ProgramData enum (CommonApplicationData or ApplicationData)
string path = Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData);
As per this doc, the Directory.CreateDirectory Method (String) will
Creates all directories and subdirectories in the specified path
unless they already exist.
So it is fine to use like this:
string path = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
string desktopFolder = Path.Combine(path, "New Folder");
Directory.CreateDirectory(desktopFolder);
You can use the Directory.Exists() method: https://msdn.microsoft.com/en-us/library/system.io.directory.exists(v=vs.110).aspx
Your code would propebly look something like this:
public static void Main()
{
// Specify the directory you want to manipulate.
string path = #"c:\MyDir";
try
{
// Determine whether the directory exists.
if (Directory.Exists(path))
{
Console.WriteLine("That path exists already.");
return;
}
// Try to create the directory.
DirectoryInfo di = Directory.CreateDirectory(path);
Console.WriteLine("The directory was created successfully at {0}.", Directory.GetCreationTime(path));
// Delete the directory.
di.Delete();
Console.WriteLine("The directory was deleted successfully.");
}
catch (Exception e)
{
Console.WriteLine("The process failed: {0}", e.ToString());
}
finally {}
}
I have had a recent issue so here is my solution,
I had to find the deployed directory
var deployedDir = Assembly.GetEntryAssembly().CodeBase;
deployedDir = Path.GetDirectoryName(deployedDir);
deployedDir = deployedDir.Replace("file:\\", "");
var pathToDirectory= Path.Combine(deployedDir, "YourFileName");
Then do what the above answers show and create the directory if it doesnt exist,
Directory.CreateDirectory(pathToDirectory)
String machineName = System.Environment.MachineName;
String filePath = #"E:\folder1\folder2\file1";
int a = filePath.IndexOf(System.IO.Path.DirectorySeparatorChar);
filePath = filePath.Substring(filePath.IndexOf(System.IO.Path.DirectorySeparatorChar) +1);
String networdPath = System.IO.Path.Combine(string.Concat(System.IO.Path.DirectorySeparatorChar, System.IO.Path.DirectorySeparatorChar), machineName, filePath);
Console.WriteLine(networdPath);
I wrote the above code using String.Concat and Path.Combine to get network path. But it is just a workaround and not a concrete solution and may fail.
Is there a concrete solution for getting a network path?
You are assuming that your E:\folder1 local path is shared as \\mypc\folder1, which in general is not true, so I doubt a general method that does what you want to do exists.
You are on the right path in implementing what you are trying to achieve. You can get more help from System.IO.Path; see Path.GetPathRoot on MSDN for returned values according to different kind of path in input
string GetNetworkPath(string path)
{
string root = Path.GetPathRoot(path);
// validate input, in your case you are expecting a path starting with a root of type "E:\"
// see Path.GetPathRoot on MSDN for returned values
if (string.IsNullOrWhiteSpace(root) || !root.Contains(":"))
{
// handle invalid input the way you prefer
// I would throw!
throw new ApplicationException("be gentle, pass to this function the expected kind of path!");
}
path = path.Remove(0, root.Length);
return Path.Combine(#"\\myPc", path);
}
I need to navigate one folder up from the current path of a file and save the same file there. How can I strip one level from the directory path? Thank you!
C:\Users\stacy.zim\AppData\Local\Temp\ICLocal\e53486af-7e5e-4c54-b9dc-d15cb55f3f55.pdf
The file will be saved to below.
C:\Users\stacy.zim\AppData\Local\Temp\e53486af-7e5e-4c54-b9dc-d15cb55f3f55.pdf
Actually it is called Parent for "One Folder Up"
System.IO.DirectoryInfo.Parent
// Method 1 Get by file
var file = new FileInfo(#"C:\Users\stacy.zim\AppData\Local\Temp\ICLocal\e53486af-7e5e-4c54-b9dc-d15cb55f3f55.pdf");
var parentDir = file.Directory == null ? null : file.Directory.Parent; // null if root
if (parentDir != null)
{
// Do something with Path.Combine(parentDir.FullName, filename.Name);
}
System.IO.Directory.GetParent()
// Method 2 Get by path
var parentDir = Directory.GetParent(#"C:\Users\stacy.zim\AppData\Local\Temp\ICLocal\");
string path = #"C:\Users\stacy.zim\AppData\Local\Temp\ICLocal\e53486af-7e5e-4c54-b9dc-d15cb55f3f55.pdf"
string directory = Path.GetDirectoryName(path); //without file name
string oneUp = Path.GetDirectoryName(directory); // Temp folder
string fileOneUp = Path.Combine(oneUp, Path.GetFileName(path));
Just be careful if the original file is in root folder - then the oneUp will be null and Path.Combine will throw an exception.
Edit:
In the code above, I split the commands on separate lines for clarity. It could be done in one line:
Path.Combine(Path.GetDirectoryName(Path.GetDirectoryName(path)), Path.GetFileName(path));
Or, as #AlexeiLevenkov suggest, you can use .. to go up one directory. In that case, you could do:
Path.Combine(Path.GetDirectoryName(path), #"..\"+Path.GetFileName(path));
which will give you the .. in your path - if you don't want that, run Path.GetFullPath on the result. Again, you need to be careful if your original file is in the root folder - unlike the first approach, which will throw an exception, this will just give you the same path.
After going through all the related stuff to copying files i am unable to find an answer to my
problem of an exception occurring while i was trying to copy a file to an empty folder in WPF application. Here is the code snippet.
public static void Copy()
{
string _finalPath;
foreach (var name in files) // name is the filename extracted using GetFileName in a list of strings
{
_finalPath = filePath; //it is the destination folder path e.g,C:\Users\Neha\Pictures\11-03-2014
if(System.IO.Directory.Exists(_finalPath))
{
_finalPath = System.IO.Path.Combine(_finalPath,name);
System.IO.File.Copy(name, _finalPath , true);
}
}
}
While debugging exception is occuring at file.copy() statement which says
"FileNotFoundException was unhandled" could not find file
i already know about the combining path and other aspects of copy but i dont know why this exception is being raised.
I am a noob to WPF please help.........
Use following code:
public static void Copy()
{
string _finalPath;
var files = System.IO.Directory.GetFiles(#"C:\"); // Here replace C:\ with your directory path.
foreach (var file in files)
{
var filename = file.Substring(file.LastIndexOf("\\") + 1); // Get the filename from absolute path
_finalPath = filePath; //it is the destination folder path e.g,C:\Users\Neha\Pictures\11-03-2014
if (System.IO.Directory.Exists(_finalPath))
{
_finalPath = System.IO.Path.Combine(_finalPath, filename);
System.IO.File.Copy(file, _finalPath, true);
}
}
}
The GetFileName ()
only returns the actual name of the file (drops the path) what you want is a full path to the file. So you getting an exception because the 'name' does not exist on your drive (path is unknown)
You're variable, name, is most likely just the file name (i.e. something.jpg). When you use the File.Copy(...) method, if you do not supply an absolute path the method assumes a path relative to the executable.
Basically, if you are running your app in, for example, C:\Projects\SomeProject\bin\Debug\SomeProject.exe, then it is assuming your file is C:\Projects\SomeProject\bin\Debug\something.jpg.
One option would be to do System.IO.Directory.GetParent() a few times. Is there a more graceful way of travelling a few folders up from where the executing assembly resides?
What I am trying to do is find a text file that resides one folder above the application folder. But the assembly itself is inside the bin, which is a few folders deep in the application folder.
Other simple way is to do this:
string path = #"C:\Folder1\Folder2\Folder3\Folder4";
string newPath = Path.GetFullPath(Path.Combine(path, #"..\..\"));
Note This goes two levels up. The result would be:
newPath = #"C:\Folder1\Folder2\";
Additional Note
Path.GetFullPath normalizes the final result based on what environment your code is running on windows/mac/mobile/...
if c:\folder1\folder2\folder3\bin is the path then the following code will return the path base folder of bin folder
//string directory=System.IO.Directory.GetParent(Environment.CurrentDirectory).ToString());
string directory=System.IO.Directory.GetParent(Environment.CurrentDirectory).ToString();
ie,c:\folder1\folder2\folder3
if you want folder2 path then you can get the directory by
string directory = System.IO.Directory.GetParent(System.IO.Directory.GetParent(Environment.CurrentDirectory).ToString()).ToString();
then you will get path as c:\folder1\folder2\
You can use ..\path to go one level up, ..\..\path to go two levels up from path.
You can use Path class too.
C# Path class
This is what worked best for me:
string parentOfStartupPath = Path.GetFullPath(Path.Combine(Application.StartupPath, #"../"));
Getting the 'right' path wasn't the problem, adding '../' obviously does that, but after that, the given string isn't usable, because it will just add the '../' at the end.
Surrounding it with Path.GetFullPath() will give you the absolute path, making it usable.
public static string AppRootDirectory()
{
string _BaseDirectory = AppDomain.CurrentDomain.BaseDirectory;
return Path.GetFullPath(Path.Combine(_BaseDirectory, #"..\..\"));
}
Maybe you could use a function if you want to declare the number of levels and put it into a function?
private String GetParents(Int32 noOfLevels, String currentpath)
{
String path = "";
for(int i=0; i< noOfLevels; i++)
{
path += #"..\";
}
path += currentpath;
return path;
}
And you could call it like this:
String path = this.GetParents(4, currentpath);
C#
string upTwoDir = Path.GetFullPath(Path.Combine(System.AppContext.BaseDirectory, #"..\..\"));
The following method searches a file beginning with the application startup path (*.exe folder). If the file is not found there, the parent folders are searched until either the file is found or the root folder has been reached. null is returned if the file was not found.
public static FileInfo FindApplicationFile(string fileName)
{
string startPath = Path.Combine(Application.StartupPath, fileName);
FileInfo file = new FileInfo(startPath);
while (!file.Exists) {
if (file.Directory.Parent == null) {
return null;
}
DirectoryInfo parentDir = file.Directory.Parent;
file = new FileInfo(Path.Combine(parentDir.FullName, file.Name));
}
return file;
}
Note: Application.StartupPath is usually used in WinForms applications, but it works in console applications as well; however, you will have to set a reference to the System.Windows.Forms assembly. You can replace Application.StartupPath by
Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) if you prefer.
I use this strategy to find configuration and resource files. This allows me to share them for multiple applications or for Debug and Release versions of an application by placing them in a common parent folder.
Hiding a looped call to Directory.GetParent(path) inside an static method is the way to go.
Messing around with ".." and Path.Combine will ultimately lead to bugs related to the operation system or simply fail due to mix up between relative paths and absolute paths.
public static class PathUtils
{
public static string MoveUp(string path, int noOfLevels)
{
string parentPath = path.TrimEnd(new[] { '/', '\\' });
for (int i=0; i< noOfLevels; i++)
{
parentPath = Directory.GetParent(parentPath ).ToString();
}
return parentPath;
}
}
this may help
string parentOfStartupPath = Path.GetFullPath(Path.Combine(Application.StartupPath, #"../../")) + "Orders.xml";
if (File.Exists(parentOfStartupPath))
{
// file found
}
If you know the folder you want to navigate to, find the index of it then substring.
var ind = Directory.GetCurrentDirectory().ToString().IndexOf("Folderame");
string productFolder = Directory.GetCurrentDirectory().ToString().Substring(0, ind);
I have some virtual directories and I cannot use Directory methods. So, I made a simple split/join function for those interested. Not as safe though.
var splitResult = filePath.Split(new[] {'/', '\\'}, StringSplitOptions.RemoveEmptyEntries);
var newFilePath = Path.Combine(filePath.Take(splitResult.Length - 1).ToArray());
So, if you want to move 4 up, you just need to change the 1 to 4 and add some checks to avoid exceptions.
Path parsing via System.IO.Directory.GetParent is possible, but would require to run same function multiple times.
Slightly simpler approach is to threat path as a normal string, split it by path separator, take out what is not necessary and then recombine string back.
var upperDir = String.Join(Path.DirectorySeparatorChar, dir.Split(Path.DirectorySeparatorChar).SkipLast(2));
Of course you can replace 2 with amount of levels you need to jump up.
Notice also that this function call to Path.GetFullPath (other answers in here) will query whether path exists using file system. Using basic string operation does not require any file system operations.