private void loadWordsFromFile()
{
words = File.ReadAllLines("C:/Users/tony/Documents/Visual Studio 2013/Projects/Hangman/Hangman/Files/test.txt");
}
private void selectWord()
{
WordsRemaining = words.Length.ToString();
HangImage = new BitmapImage(new Uri("C:/Users/tony/Documents/Visual Studio 2013/Projects/Hangman/Hangman/Files/" + wrongGuesses + ".png"));
}
These are my paths. Could you please show me how to make the paths properly?
You can use this to get the current execution path
Uri executingPathUri = new Uri(Assembly.GetExecutingAssembly().GetName().CodeBase);
string executionFolderPath = Path.GetDirectoryName(executingPathUri.LocalPath);
Then, you can have a folder in your deployment directory that contains the files that you need.
Please never try to concatenate path using '+' operator. Always use
Path.Combine(.....)
public static string Combine(string path1, string path2, string path3, string path4);
Related
i am currently trying to redirect a path to save an image in a folder.
The Startup path is:
C:\Users\Donald\Documents\Visual Studio 2013\Projects\DesktopApplication\DesktopApplication\bin\Debug
I am trying to change it so its like:
C:\Users\Donald\Documents\Visual Studio 2013\Projects\DesktopApplication\DesktopApplication
The code i am currently using is:
private void browseBtn_Click(object sender, EventArgs e)
{
try
{
OpenFileDialog open = new OpenFileDialog();
//open directory
open.Filter = "JPG Files (*.jpg)|*.jpg|PNG Files (*.png)|*.png|ALL Files (*.*)|*.*";
open.FilterIndex = 1;
if(open.ShowDialog() == DialogResult.OK)
{
if(open.CheckFileExists)
{
string paths = Application.StartupPath.Substring(0, (Application.StartupPath.Length - 10));
System.IO.File.Copy(open.FileName, paths + "\\Images\\sss.jpg");
}
}
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
}
Any help or ideas on the matter? why isnt it taking off the characters so i can use images as the path
There is nothing wrong with your code:
string source =
#"C:\Users\Donald\Documents\Visual Studio 2013\Projects\DesktopApplication\DesktopApplication\bin\Debug";
string path = source.Substring(0, source.Length - 10);
Console.WriteLine(path);
//resulting in C:\Users\Donald\Documents\Visual Studio 2013\Projects\DesktopApplication\DesktopApplication
....If:
You build the project as "Debug", not "Release"
The image directory and the sss.jpg image do exist.
But the way to get the path the way you do now is just... unsafe (at the very least). Try to use Path.Combine and string.Split("\\") instead:
string source = #"C:\Users\Donald\Documents\Visual Studio 2013\Projects\DesktopApplication\DesktopApplication\bin\Debug";
string[] items = source.Split('\\');
string path = Path.Combine(string.Join("\\", items.Take(items.Length - 2)), "Images\\sss.jpg");
It seems, that you actually want to cut 2 subdirectories off and then combine with \Images\sss.jpg:
String source =
#"C:\Users\Donald\Documents\Visual Studio 2013\Projects\DesktopApplication\DesktopApplication\bin\Debug";
String[] items = source.Split(new Char[] {
Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar });
String path = String.Join(
Path.DirectorySeparatorChar.ToString(), items.Take(items.Length - 2));
String result = Path.Combine(path, #"Images\sss.jpg");
There's nothing wrong with your code and should work just fine so long as the Images directory exists. Just use
if (!Directory.Exists(Path.Combine(path, "Images")))
Directory.Create(Path.Combine(path, "Images")))
Is there any reason not to just leverage DirectoryInfo? It looks like you just want to go up two directories. You should be able to use DirectoryInfo.Parent to get the path you need without needing to do string manipulation.
DirectoryInfo startupDirectory = new DirectoryInfo(Application.StartupPath);
DirectoryInfo twoDirectoriesUp = startupDirectory.Parent.Parent;
string fullDirectoryName = twoDirectoriesUp.FullName;
I have an Image in my application and I have a picture in my WinForms.
public static string Correct_Icons = #"C:\Users\xyz\Documents\Visual Studio 2008\Projects\FileShareMgmt\FileShareMgmt\Resources\Correct.png";
public static string warning_Icon = #"C:\Users\xyz\Documents\Visual Studio 2008\Projects\FileShareMgmt\FileShareMgmt\Resources\Warning.png";
cell.Value = Image.FromFile("Resources/warning_Icon);
But I just want to use a relative path and not the full path like above.
For example something like this:
public static string Correct_Icons = "\Resources\Correct.png";
and cont.
..../
not working. Any suggestions?
For my program, Path.GetDirectoryName (Assembly.GetExecutingAssembly().Location) returns
C:\code\test\Junk\bin\Debug.
cell.Value = Image.FromFile(
Path.Combine (
Path.GetDirectoryName (Assembly.GetExecutingAssembly().Location),
"Resources/warning_Icon"));
Of course, usually you would embed the resources in your assembly unless you want to change them without a recompile.
My issue was solved after this solution:
string[] s = { "\\bin" };
string path = Application.StartupPath.Split(s, StringSplitOptions.None)[0] + "\\Images\\On24.png";
How do I convert a relative path to an absolute path in a Windows application?
I know we can use server.MapPath() in ASP.NET. But what can we do in a Windows application?
I mean, if there is a .NET built-in function that can handle that...
Have you tried:
string absolute = Path.GetFullPath(relative);
? Note that that will use the current working directory of the process, not the directory containing the executable. If that doesn't help, please clarify your question.
If you want to get the path relative to your .exe then use
string absolute = Path.Combine(Application.ExecutablePath, relative);
This one works for paths on different drives, for drive-relative paths and for actual relative paths. Heck, it even works if the basePath isn't actually absolute; it always uses the current working directory as final fallback.
public static String GetAbsolutePath(String path)
{
return GetAbsolutePath(null, path);
}
public static String GetAbsolutePath(String basePath, String path)
{
if (path == null)
return null;
if (basePath == null)
basePath = Path.GetFullPath("."); // quick way of getting current working directory
else
basePath = GetAbsolutePath(null, basePath); // to be REALLY sure ;)
String finalPath;
// specific for windows paths starting on \ - they need the drive added to them.
// I constructed this piece like this for possible Mono support.
if (!Path.IsPathRooted(path) || "\\".Equals(Path.GetPathRoot(path)))
{
if (path.StartsWith(Path.DirectorySeparatorChar.ToString()))
finalPath = Path.Combine(Path.GetPathRoot(basePath), path.TrimStart(Path.DirectorySeparatorChar));
else
finalPath = Path.Combine(basePath, path);
}
else
finalPath = path;
// resolves any internal "..\" to get the true full path.
return Path.GetFullPath(finalPath);
}
It's a bit older topic, but it might be useful for someone.
I have solved a similar problem, but in my case, the path was not at the beginning of the text.
So here is my solution:
public static class StringExtension
{
private const string parentSymbol = "..\\";
private const string absoluteSymbol = ".\\";
public static String AbsolutePath(this string relativePath)
{
string replacePath = AppDomain.CurrentDomain.BaseDirectory;
int parentStart = relativePath.IndexOf(parentSymbol);
int absoluteStart = relativePath.IndexOf(absoluteSymbol);
if (parentStart >= 0)
{
int parentLength = 0;
while (relativePath.Substring(parentStart + parentLength).Contains(parentSymbol))
{
replacePath = new DirectoryInfo(replacePath).Parent.FullName;
parentLength = parentLength + parentSymbol.Length;
};
relativePath = relativePath.Replace(relativePath.Substring(parentStart, parentLength), string.Format("{0}\\", replacePath));
}
else if (absoluteStart >= 0)
{
relativePath = relativePath.Replace(".\\", replacePath);
}
return relativePath;
}
}
Example:
Data Source=.\Data\Data.sdf;Persist Security Info=False;
Data Source=..\..\bin\Debug\Data\Data.sdf;Persist Security Info=False;
I want to convert a virtual file path to a physical file path in a windows service.
I know what the physical path is for the virtual directory, so I have the following function that works, but feels like a fudge:
public static string GetPhysicalPathFromVirtual(string rootPath, string virtualPath)
{
int trailingSlash = virtualPath.IndexOf('/', 1) + 1;
int length = virtualPath.Length - trailingSlash;
string stripped = virtualPath.Substring(trailingSlash, length);
stripped = stripped.Replace(#"/", #"\");
return Path.Combine(rootPath, stripped);
}
The following example:
string test = FileHelper.GetPhysicalPathFromVirtual(#"T:\generateddocuments\output\", #"/virtualroot/folder/myfile.pdf");
Returns: T:\generateddocuments\output\folder\myfile.pdf
Is there a more elegant way to do this?
Uri class may be of help for your task.
Please note that using relative paths in services can expose a huge security hole so you should be very defensive when you code them.
Here's what I came up with:
public static string GetPhysicalPathFromVirtual(string rootPath, string virtualPath)
{
const string mandatoryVirtualPrefix = "/virtualroot/";
if (!virtualPath.StartsWith(mandatoryVirtualPrefix))
throw new ArgumentOutOfRangeException(virtualPath, string.Format("Virtual '{0}' path must start with mandatory prefix '{1}'", virtualPath, mandatoryVirtualPrefix));
var relativePath = virtualPath.Substring(mandatoryVirtualPrefix.Length);
var rootUri = new Uri(rootPath, UriKind.Absolute);
var relativeUri = new Uri(relativePath, UriKind.Relative);
var absoluteUri = new Uri(rootUri, relativeUri);
if (!rootUri.IsBaseOf(absoluteUri))
throw new ArgumentOutOfRangeException(virtualPath, string.Format("Virtual path '{0}' can't be outside of root '{1}'", virtualPath, rootPath));
return absoluteUri.LocalPath;
}
I'm trying to join a Windows path with a relative path using Path.Combine.
However, Path.Combine(#"C:\blah",#"..\bling") returns C:\blah\..\bling instead of C:\bling\.
Does anyone know how to accomplish this without writing my own relative path resolver (which shouldn't be too hard)?
What Works:
string relativePath = "..\\bling.txt";
string baseDirectory = "C:\\blah\\";
string absolutePath = Path.GetFullPath(baseDirectory + relativePath);
(result: absolutePath="C:\bling.txt")
What doesn't work
string relativePath = "..\\bling.txt";
Uri baseAbsoluteUri = new Uri("C:\\blah\\");
string absolutePath = new Uri(baseAbsoluteUri, relativePath).AbsolutePath;
(result: absolutePath="C:/blah/bling.txt")
Call Path.GetFullPath on the combined path http://msdn.microsoft.com/en-us/library/system.io.path.getfullpath.aspx
> Path.GetFullPath(Path.Combine(#"C:\blah\",#"..\bling"))
C:\bling
(I agree Path.Combine ought to do this by itself)
Path.GetFullPath(#"c:\windows\temp\..\system32")?
For windows universal apps Path.GetFullPath() is not available, you can use the System.Uri class instead:
Uri uri = new Uri(Path.Combine(#"C:\blah\",#"..\bling"));
Console.WriteLine(uri.LocalPath);
This will give you exactly what you need (path does NOT have to exist for this to work)
DirectoryInfo di = new DirectoryInfo(#"C:\blah\..\bling");
string cleanPath = di.FullName;
Path.GetFullPath() does not work with relative paths.
Here's the solution that works with both relative + absolute paths. It works on both Linux + Windows and it keeps the .. as expected in the beginning of the text (at rest they will be normalized). The solution still relies on Path.GetFullPath to do the fix with a small workaround.
It's an extension method so use it like text.Canonicalize()
/// <summary>
/// Fixes "../.." etc
/// </summary>
public static string Canonicalize(this string path)
{
if (path.IsAbsolutePath())
return Path.GetFullPath(path);
var fakeRoot = Environment.CurrentDirectory; // Gives us a cross platform full path
var combined = Path.Combine(fakeRoot, path);
combined = Path.GetFullPath(combined);
return combined.RelativeTo(fakeRoot);
}
private static bool IsAbsolutePath(this string path)
{
if (path == null) throw new ArgumentNullException(nameof(path));
return
Path.IsPathRooted(path)
&& !Path.GetPathRoot(path).Equals(Path.DirectorySeparatorChar.ToString(), StringComparison.Ordinal)
&& !Path.GetPathRoot(path).Equals(Path.AltDirectorySeparatorChar.ToString(), StringComparison.Ordinal);
}
private static string RelativeTo(this string filespec, string folder)
{
var pathUri = new Uri(filespec);
// Folders must end in a slash
if (!folder.EndsWith(Path.DirectorySeparatorChar.ToString())) folder += Path.DirectorySeparatorChar;
var folderUri = new Uri(folder);
return Uri.UnescapeDataString(folderUri.MakeRelativeUri(pathUri).ToString()
.Replace('/', Path.DirectorySeparatorChar));
}
Be careful with Backslashes, don't forget them (neither use twice:)
string relativePath = "..\\bling.txt";
string baseDirectory = "C:\\blah\\";
//OR:
//string relativePath = "\\..\\bling.txt";
//string baseDirectory = "C:\\blah";
//THEN
string absolutePath = Path.GetFullPath(baseDirectory + relativePath);