I have this method:
private List<string> offline(string targetDirectory)
{
if (targetDirectory.Contains("http://"))
{
MessageBox.Show("true");
}
DirectoryInfo di = new DirectoryInfo(targetDirectory);
List<string> directories = new List<string>();
try
{
string[] dirs = Directory.GetDirectories(targetDirectory,"*.*",SearchOption.TopDirectoryOnly);
for (int i = 0; i < dirs.Length; i++)
{
string t = "http://" + dirs[i];
directories.Add(t);
}
}
catch
{
MessageBox.Show("hgjghj");
}
return directories;
}
This is the part:
if (targetDirectory.Contains("http://"))
{
MessageBox.Show("true");
}
I'm getting a directory which give me all the directories in this directory and I'm adding to each directory the string "http://".
The problem is when next time a directory is getting to the function its coming with "http://"
For example: http://c:\\ or http://c:\\windows
And then the line
DirectoryInfo di = new DirectoryInfo(targetDirectory); // throws exception.
So I want that each time a directory is getting to the function to check if it starts with "http://" in the beginning, strip the "http://" part, get all the directories, and then add to each directory "http://" like now.
How can I remove "http://"?
I would be stricter than using Contains - I'd use StartsWith, and then Substring:
if (targetDirectory.StartsWith("http://"))
{
targetDirectory = targetDirectory.Substring("http://".Length);
}
Or wrap it in a helper method:
public static string StripPrefix(string text, string prefix)
{
return text.StartsWith(prefix) ? text.Substring(prefix.Length) : text;
}
It's not clear to me why you're putting the http:// as a prefix anyway though, to be honest. I can't see how you'd expect a directory name prefixed with http:// to be a valid URL. Perhaps if you could explain why you're doing it, we could suggest a better approach.
(Also, I really hope you don't have a try/catch block like that in your real code, and that normally you follow .NET naming conventions.)
The problem is how can i remove the http:// ?
You may use string.Replace, and replace the string with an empty string.
targetDirectory = targetDirectory.Replace("http://","");
or
targetDirectory = targetDirectory.Replace("http://",string.Empty);
both of them are same
Try this:
if(example.StartsWith("http://"))
{
example.substring(7);
}
You can always use the String.Replace to remove / replace characters in the string.
Exampel:
targetDirectory = targetDirectory.Replace("http://", string.Empty);
And you can check if the string begins with Http:// by doing
if(targetDirectory.StartsWith("http://"))
You can use the replace characters in the string by string.Replace
if (targetDirectory.Contains("http://"))
{
targetDirectory = targetDirectory.Replace("http://",string.Empty);
}
Related
I am having a bit of a problem with Escape characters is a string that I am reading from a txt file,
They are causing an error later in my program, they need to be removed but I can't seem to filter them out
public static List<string> loadData(string type)
{
List<string> dataList = new List<string>();
try
{
string path = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "Data");
string text = File.ReadAllText(path + type);
string[] dataArray = text.Split(',');
foreach (var data in dataArray)
{
string dataUnescaped = Regex.Unescape(data);
if (!string.IsNullOrEmpty(dataUnescaped) && (!dataUnescaped.Contains(#"\r") || (!dataUnescaped.Contains(#"\n"))))
{
dataList.Add(data);
}
}
return dataList;
}
catch(Exception e)
{
Console.WriteLine(e);
return dataList;
}
}
I have tried text.Replace(#"\r\n")
and an if statement but I just cant seem to remove them from my string
Any ideas will be appreciated
If you add the # Sign before a string that means you specify that you want a string without having to escape any characters.
So if you wanted a path without # you would need to do this:
string s = "c:\\myfolder\\myfile.txt"
But if you add the # before your \n\r isntead of the escaped sequence Windows New Line you would instead get the string "\n\r".
So this will result in you removing all occurrences of the string "\n\r". Instead of NewLines like you want to:
text.Replace(#"\r\n")
To fix that you would need to use:
text = text.Replace(Environment.NewLine, string.Empty);
You can use Environment.NewLine as well instead of \r and \n, because Environment knows which OS you are currently on and change the replaced character depeding on that.
I want to get the page name from a URI for instance if I have
"/Pages/Alarm/AlarmClockPage.xaml"
I want to get AlarmClockPage
I tried
//usage GetSubstring("/", ".", "/Pages/Alarm/AlarmClockPage.xaml")
public static string GetSubstring(string a, string b, string c)
{
string str = c.Substring((c.IndexOf(a) + a.Length),
(c.IndexOf(b) - c.IndexOf(a) - a.Length));
return str;
}
But because the string being search may contain one or more forward slashes, I don't think this method work in such case.
So how do I consider the multiple forward slashes that may present?
Why don't you use method which is already in the framework?
System.IO.Path.GetFileNameWithoutExtension(#"/Pages/Alarm/AlarmClockPage.xaml");
If you only want to use string functions, you may try:
var startIdx = pathString.LastIndexOf(#"/");
var endIdx = pathString.LastIndexOf(".");
if(endIdx!=-1)
{
fileName = pathString.Substring(startIdx,endIdx);
}
else
{
fileName = pathString.Substring(startIdx);
}
It gives file name from a given file path. try this
string pageName = System.IO.Path.GetFileName(#"/Pages/Alarm/AlarmClockPage.xaml");
For example,
string path = #"C:\User\Desktop\Drop\images\";
I need to get only #"C:\User\Desktop\Drop\
Is there any easy way of doing this?
You can use the Path and Directory classes:
DirectoryInfo parentDir = Directory.GetParent(Path.GetDirectoryName(path));
string parent = parentDir.FullName;
Note that you would get a different result if the path doesn't end with the directory-separator char \. Then images would be understood as filename and not as directory.
You can also use a subsequent call of Path.GetDirectoryName
string parent = Path.GetDirectoryName(Path.GetDirectoryName(path));
This behaviour is documented here:
Because the returned path does not include the DirectorySeparatorChar
or AltDirectorySeparatorChar, passing the returned path back into the
GetDirectoryName method will result in the truncation of one folder
level per subsequent call on the result string. For example, passing
the path "C:\Directory\SubDirectory\test.txt" into the
GetDirectoryName method will return "C:\Directory\SubDirectory".
Passing that string, "C:\Directory\SubDirectory", into
GetDirectoryName will result in "C:\Directory".
This will return "C:\User\Desktop\Drop\" e.g. everything but the last subdir
string path = #"C:\User\Desktop\Drop\images";
string sub = path.Substring(0, path.LastIndexOf(#"\") + 1);
Another solution if you have a trailing slash:
string path = #"C:\User\Desktop\Drop\images\";
var splitedPath = path.Split('\\');
var output = String.Join(#"\", splitedPath.Take(splitedPath.Length - 2));
var parent = "";
If(path.EndsWith(System.IO.Path.DirectorySeparatorChar) || path.EndsWith(System.IO.Path.AltDirectorySeparatorChar))
{
parent = Path.GetDirectoryName(Path.GetDirectoryName(path));
parent = Directory.GetParent(Path.GetDirectoryName(path)).FullName;
}
else
parent = Path.GetDirectoryName(path);
As i commented GetDirectoryName is self collapsing it returns path without tralling slash - allowing to get next directory.Using Directory.GetParent for then clouse is also valid.
Short Answer :)
path = Directory.GetParent(Directory.GetParent(path)).ToString();
Example on the bottom of the page probably will help:
http://msdn.microsoft.com/en-us/library/system.io.path.getdirectoryname(v=vs.110).aspx
using System;
namespace Programs
{
public class Program
{
public static void Main(string[] args)
{
string inputText = #"C:\User\Desktop\Drop\images\";
Console.WriteLine(inputText.Substring(0, 21));
}
}
}
Output:
C:\User\Desktop\Drop\
There is probably some simple way to do this using the File or Path classes, but you could also solve it by doing something like this (Note: not tested):
string fullPath = "C:\User\Desktop\Drop\images\";
string[] allDirs = fullPath.split(System.IO.Path.PathSeparator);
string lastDir = allDirs[(allDirs.length - 1)];
string secondToLastDir= allDirs[(allDirs.length - 2)];
// etc...
I have a list of filename with full path which I need to remove the filename and part of the file path considering a filter list I have.
Path.GetDirectoryName(file)
Does part of the job but I was wondering if there is a simple way to filter the paths using .Net 2.0 to remove part of it.
For example:
if I have the path + filename equal toC:\my documents\my folder\my other folder\filename.exe and all I need is what is above my folder\ means I need to extract only my other folder from it.
UPDATE:
The filter list is a text box with folder names separated by a , so I just have partial names on it like the above example the filter here would be my folder
Current Solution based on Rob's code:
string relativeFolder = null;
string file = #"C:\foo\bar\magic\bar.txt";
string folder = Path.GetDirectoryName(file);
string[] paths = folder.Split(Path.DirectorySeparatorChar);
string[] filterArray = iFilter.Text.Split(',');
foreach (string filter in filterArray)
{
int startAfter = Array.IndexOf(paths, filter) + 1;
if (startAfter > 0)
{
relativeFolder = string.Join(Path.DirectorySeparatorChar.ToString(), paths, startAfter, paths.Length - startAfter);
break;
}
}
How about something like this:
private static string GetRightPartOfPath(string path, string startAfterPart)
{
// use the correct seperator for the environment
var pathParts = path.Split(Path.DirectorySeparatorChar);
// this assumes a case sensitive check. If you don't want this, you may want to loop through the pathParts looking
// for your "startAfterPath" with a StringComparison.OrdinalIgnoreCase check instead
int startAfter = Array.IndexOf(pathParts, startAfterPart);
if (startAfter == -1)
{
// path not found
return null;
}
// try and work out if last part was a directory - if not, drop the last part as we don't want the filename
var lastPartWasDirectory = pathParts[pathParts.Length - 1].EndsWith(Path.DirectorySeparatorChar.ToString());
return string.Join(
Path.DirectorySeparatorChar.ToString(),
pathParts, startAfter,
pathParts.Length - startAfter - (lastPartWasDirectory?0:1));
}
This method attempts to work out if the last part is a filename and drops it if it is.
Calling it with
GetRightPartOfPath(#"C:\my documents\my folder\my other folder\filename.exe", "my folder");
returns
my folder\my other folder
Calling it with
GetRightPartOfPath(#"C:\my documents\my folder\my other folder\", "my folder");
returns the same.
you could use this method to split the path by "\" sign (or "/" in Unix environments). After this you get an array of strings back and you can pick what you need.
public static String[] SplitPath(string path)
{
String[] pathSeparators = new String[]
{
Path.DirectorySeparatorChar.ToString()
};
return path.Split(pathSeparators, StringSplitOptions.RemoveEmptyEntries);
}
Is there anything built into System.IO.Path that gives me just the filepath?
For example, if I have a string
#"c:\webserver\public\myCompany\configs\promo.xml",
is there any BCL method that will give me
"c:\webserver\public\myCompany\configs\"?
Path.GetDirectoryName()... but you need to know that the path you are passing to it does contain a file name; it simply removes the final bit from the path, whether it is a file name or directory name (it actually has no idea which).
You could validate first by testing File.Exists() and/or Directory.Exists() on your path first to see if you need to call Path.GetDirectoryName
Console.WriteLine(Path.GetDirectoryName(#"C:\hello\my\dear\world.hm"));
Path.GetDirectoryName() returns the directory name, so for what you want (with the trailing reverse solidus character) you could call Path.GetDirectoryName(filePath) + Path.DirectorySeparatorChar.
string fileAndPath = #"c:\webserver\public\myCompany\configs\promo.xml";
string currentDirectory = Path.GetDirectoryName(fileAndPath);
string fullPathOnly = Path.GetFullPath(currentDirectory);
currentDirectory: c:\webserver\public\myCompany\configs
fullPathOnly: c:\webserver\public\myCompany\configs
Use GetParent() as shown, works nicely. Add error checking as you need.
var fn = openFileDialogSapTable.FileName;
var currentPath = Path.GetFullPath( fn );
currentPath = Directory.GetParent(currentPath).FullName;
I used this and it works well:
string[] filePaths = Directory.GetFiles(Path.GetDirectoryName(dialog.FileName));
foreach (string file in filePaths)
{
if (comboBox1.SelectedItem.ToString() == "")
{
if (file.Contains("c"))
{
comboBox2.Items.Add(Path.GetFileName(file));
}
}
}