This question already has answers here:
Using / or \\ for folder paths in C#
(5 answers)
Closed 7 years ago.
I have this function in a certain Class1:
public void function1(String path){
this.excel = new Application();
this.wbooks = excel.Workbooks;
this.wb = wbooks.Open(path);
String rootPath = wb.Path+"//..//..//";
String nPath = String.Format("{0}//Loads//{1}//{2}",rootPath,name1,name2);
String outputDir = String.Format("{0}//Input//{1}//{2}", rootPath, name1, name2);
String erroDir = String.Format("{0}//Erro//{1}//{2}", rootPath, name1, name2);
for(int i = 0; i < size; i++){
String[] array2 = File.ReadAllLines(String.Format("{0}//{1}_{2}.txt", nPath, name1, i.ToString()));
//code
Directory.CreateDirectory(erroDir);
File.WriteAllLines(String.Format("{0}//erro_{1}_{2}.txt", erroDir, name1, i.ToString()), array);
Directory.CreateDirectory(outputDir);
File.WriteAllLines(String.Format("{0}//output_{1}.txt", outputDir, name2), array);
}
}
This function from a class and is being called like this in the main function:
String path = "C:\\Users\\myUsername\\Desktop\\myFolder\\";
Class1 temp = new Class1();
temp.function1(path);
Why are the paths made in the function working?Shouldnt path be made "\\" instead of "//".
Why are the paths made in the function working?Shouldnt path be made "\" instead of "//".
Yes, they should. But Windows is 'smart'. It tries to determine what you actually meant to ask, in this case, if the file path starts with C: for example, it 'knows' it is a local file path, and thus it tries to interpret it as such.
Note that not all programs are that smart. Some .NET build tools for example (not C# itself) are known for some bugs with handling such file paths.
Related
This question already has answers here:
Given a filesystem path, is there a shorter way to extract the filename without its extension?
(10 answers)
Closed 10 months ago.
Suppose I have an array of strings with full file names and paths. For example
string[] filesArray = Directory.GetFiles(#"C:\dir", "*", SearchOption.AllDirectories);
Now let's say we have the following data in the array:
filesArray[0] = "C:\dir\file1.txt"
filesArray[1] = "C:\dir\subdir1\file2.txt"
filesArrat[2] = "C:\dir\subdir1\subdir2\file3.txt"
... etc.
Now I want a new array, that will store only the files' names, something like this:
nameArray[0] = "file1.txt"
nameArray[1] = "file2.txt"
nameArray[2] = "file3.txt"
What is the best way to do it, using string array only, without storing the full FileInfo class objects?
Using LINQ it's pretty simple
string[] nameArray = filesArray.Select(p => Path.GetFileName(p)).ToArray()
This question already has answers here:
Getting file names without extensions
(14 answers)
Closed 9 years ago.
It seems a simple one but I confused to get it.
Here is the case:
I have a complete file name like abdcd.pdf or efghijf.jpg or jklmn.jpeg,
Now I have to get only the file name as abdcd or efghijf or jklmn
Use Path class static method
result = Path.GetFileNameWithoutExtension(fileName);
String f = "file.jpg";
int lastIndex = f.LastIndexOf('.');
Console.WriteLine(f.Substring(0, lastIndex));
Or, like the others suggested, you can also use
Path.GetFileNameWithoutExtension(f)
You could use String.Substring(), but I recommend Path.GetFileNameWithoutExtension() for this task:
// returns "test"
Path.GetFileNameWithoutExtension("test.txt")
Go to the msdn documentation
This method is essentially implemented like this:
int index = path.LastIndexOf('.');
return index == -1 ? path : path.Substring(0, index);
I would use the API call.
http://msdn.microsoft.com/en-us/library/system.io.path.getfilenamewithoutextension(v=vs.110).aspx
string fileName = #"C:\mydir\myfile.ext";
string path = #"C:\mydir\";
string result;
result = Path.GetFileNameWithoutExtension(fileName);
Console.WriteLine("GetFileNameWithoutExtension('{0}') returns '{1}'",
fileName, result);
result = Path.GetFileName(path);
Console.WriteLine("GetFileName('{0}') returns '{1}'",
path, result);
// This code produces output similar to the following:
//
// GetFileNameWithoutExtension('C:\mydir\myfile.ext') returns 'myfile'
// GetFileName('C:\mydir\') returns ''
I would use Path static method: Path.GetFileNameWithoutExtension()
There is actually a method for that:
http://msdn.microsoft.com/en-us/library/system.io.path.getfilenamewithoutextension(v=vs.110).aspx
Use the GetFileNameWithoutExtension static method like this:
result = Path.GetFileNameWithoutExtension(fileName);
From the MSDN:
The string returned by GetFileName, minus the last period (.) and all characters following it.
I'm trying to write a nifty content loader in XNA to avoid having to individually load each asset. However, I'm having trouble describing directory locations because the default directory for File operations is the location of the exe, but XNA's Content.Load uses a default directory of the Content folder.
foreach (string subD in Directory.GetDirectories("..\\..\\..\\..\\Happy WorkerContent\\gfx\\", "*.*", SearchOption.AllDirectories))
{
foreach (string s in Directory.GetFiles(subD))
{
string file = Path.GetFileNameWithoutExtension(s);
if (Enum.IsDefined(typeof(Tex), file))
{
Console.WriteLine(subD);
Console.WriteLine(file);
GXDict.Add(Path.GetFileNameWithoutExtension(s), GV.C_Game1.Content.Load<Texture2D>(subD + "\\" + file));
}
}
}
My error is because subD is, for example, "........\Happy WorkerContent\gfx\level entities\terrains", but Content.Load expects "gfx\level entities\terrains".
I could do something like subD.Substring(32), but this seems messy, especially if I rename any folders or anything later (and may not work in the published version?). Is there a good way to say "I only want the part of the file which is after the "Happy WorkerContent" directory?
You could write a method to return the text following a particular target string.
Then if you needed to search for a different string, you'd just need to pass a different target string to the method.
For example:
// Returns the contents of text following the target string,
// or "" if the target string wasn't found.
public static string ContentAfter(string text, string target)
{
int index = text.IndexOf(target);
if (index >= 0)
return text.Substring(index + target.Length);
else
return "";
}
Then you'd call it like:
string test = "..\\..\\..\\..\\Happy WorkerContent\\gfx\\whatever";
string target = "\\Happy WorkerContent\\";
string following = ContentAfter(test, target);
That wouldn't work so great if you had two strings matching the target string in the text. The method would return all the text after the first match, which would include the second target string of course.
I am writing a C# program which reads certain tags from files and based on tag values it creates a directory structure.
Now there could be anything in those tags,
If the tag name is not suitable for a directory name I have to prepare it to make it suitable by replacing those characters with anything suitable. So that directory creation does not fail.
I was using following code but I realised this is not enough..
path = path.replace("/","-");
path = path.replace("\\","-");
please advise what's the best way to do it..
thanks,
Import System.IO namespace and for path use
Path.GetInvalidPathChars
and for filename use
Path.GetInvalidFileNameChars
For Eg
string filename = "salmnas dlajhdla kjha;dmas'lkasn";
foreach (char c in Path.GetInvalidFileNameChars())
filename = filename.Replace(System.Char.ToString(c), "");
foreach (char c in Path.GetInvalidPathChars())
filename = filename.Replace(System.Char.ToString(c), "");
Then u can use Path.Combine to add tags to create a path
string mypath = Path.Combine(#"C:\", "First_Tag", "Second_Tag");
//return C:\First_Tag\Second_Tag
You can use the full list of invalid characters here to handle the replacement as desired. These are available directly via the Path.GetInvalidFileNameChars and Path.GetInvalidPathChars methods.
The characters you must now use are: ? < > | : \ / * "
string PathFix(string path)
{
List<string> _forbiddenChars = new List<string>();
_forbiddenChars.Add("?");
_forbiddenChars.Add("<");
_forbiddenChars.Add(">");
_forbiddenChars.Add(":");
_forbiddenChars.Add("|");
_forbiddenChars.Add("\\");
_forbiddenChars.Add("/");
_forbiddenChars.Add("*");
_forbiddenChars.Add("\"");
for (int i = 0; i < _forbiddenChars.Count; i++)
{
path = path.Replace(_forbiddenChars[i], "");
}
return path;
}
Tip: You can't include double-quote ("), but you can include 2 quotes ('').
In this case:
string PathFix(string path)
{
List<string> _forbiddenChars = new List<string>();
_forbiddenChars.Add("?");
_forbiddenChars.Add("<");
_forbiddenChars.Add(">");
_forbiddenChars.Add(":");
_forbiddenChars.Add("|");
_forbiddenChars.Add("\\");
_forbiddenChars.Add("/");
_forbiddenChars.Add("*");
//_forbiddenChars.Add("\""); Do not delete the double-quote character, so we could replace it with 2 quotes (before the return).
for (int i = 0; i < _forbiddenChars.Count; i++)
{
path = path.Replace(_forbiddenChars[i], "");
}
path = path.Replace("\"", "''"); //Replacement here
return path;
}
You'll of course use only one of those (or combine them to one function with a bool parameter for replacing the quote, if needed)
The correct answer of Nikhil Agrawal has some syntax errors.
Just for the reference, here is a compiling version:
public static string MakeValidFolderNameSimple(string folderName)
{
if (string.IsNullOrEmpty(folderName)) return folderName;
foreach (var c in System.IO.Path.GetInvalidFileNameChars())
folderName = folderName.Replace(c.ToString(), string.Empty);
foreach (var c in System.IO.Path.GetInvalidPathChars())
folderName = folderName.Replace(c.ToString(), string.Empty);
return folderName;
}
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Best way to determine if two path reference to same file in C#
So I have two Windows filenames I need to compare to determine if they are the same. One the user gave me, one given to me by another program. So how should you compare:
C:\Program Files\Application1\APP.EXE
C:\Progra~1\Applic~1\APP.EXE
C:\program files\applic~1\app.exe
I can't seem to find a way to consistently 'normalize' the path, I tried using Path.GetFullPath(path) and new FileInfo(path).FullName and neither seem to resolve this.
UPDATE:
Path.GetFullPath(path) will correct the short to long name conversion but it will not normalize case. Thus a StringComparer.OrdinalIgnoreCase.Equals(path1, path2) is required.
You will need Path.GetFullPath() + case insensitive string comparison.
Running the following code:
using System;
using System.IO;
class Test {
static void Main ()
{
//string [] str = new string[] {#"c:\program files\vim\vim72", #"c:\progra~1\vim\vim72"};
string [] str = new string[] {#"c:\program files\Refere~1\microsoft", #"c:\progra~1\Refere~1\microsoft"};
foreach (string s in str) {
// Call s = Environment.ExpandEnvironmentVariables (s) if needed.
Console.WriteLine (Path.GetFullPath (s));
}
}
}
gives:
c:\program files\Reference Assemblies\microsoft
c:\Program Files\Reference Assemblies\microsoft
a short test run says that the below code will work for the paths given:
bool CompareFileName(string file1, string file2)
{
var directory1 = Path.GetDirectoryName(file1);
var directory2 = Path.GetDirectoryName(file2);
var fileName1 = Path.GetFileName(file1);
var fileName2 = Path.GetFileName(file2);
return directory1.Equals(directory2, StringComparison.InvariantCultureIgnoreCase) &&
fileName1.Equals(fileName2, StringComparison.InvariantCultureIgnoreCase);
}
this assumes windows platform (an assumption made due to the windows centric paths given as example paths)
I use the FileInfo object. If you create a fileinfo object of a file that actually exists the Directory property gives a nicely formatted path name.
You also get the additional benefit of being able to test if the file actually exists.