Does System.IO.File.Move not support previously-defined strings? - c#

For example, something like this fails:
string oldfile = (#"C:\oldfile.txt");
string newfile = (#"C:\newfolder\newfile.txt");
System.IO.File.Move(oldfile, newfile);
Program crashes with "The given path's format is not supported."
EDIT: I'm doing this in a Windows Forms project vs. Console project, does that make a difference? Intuitively I wouldn't think it should, but you never know...

The problem is the mixture of the verbatim string format ( #"..." ) and escaping slashes ( "\" )
The second piece of code
string oldFile = #"C:\\oldfile.txt"
creates a path of 'C:\\oldfile.txt' which is not recognised as a valid path.
Either use the first version you gave
string oldFile = #"C:\oldfile.txt"
or
string oldFile = "C:\\oldfile.txt"

string oldfile = (#"C:\oldfile.txt");
string newfile = (#"C:\newfolder\newfile.txt");
System.IO.File.Move(oldfile , newfile );
or
string oldfile = ("C:\oldfile.txt");
string newfile = (#"C:\newfolder\newfile.txt");
System.IO.File.Move(oldfile , newfile );
if the direcotry not exist, create it with Directory.CreateDirectory

In a string literal prefixed with # the escape sequences starting with \ are disabled. This is convenient for filepaths since \ is the path separator and you don't want it to start an escape sequence.
You simply have to use the below one:
string oldfile = ("C:\\oldfile.txt");
string newfile = ("C:\\newfolder\\newfile.txt");
System.IO.File.Move(oldfile, newfile);
OR
string oldfile = (#"C:\oldfile.txt");
string newfile = (#"C:\newfolder\newfile.txt");
System.IO.File.Move(oldfile, newfile);
It works without crash.

Refer this MSDN Article
MSDN says to use like this
string path = #"C:\oldfile.txt";
string path2 = #"C:\newfolder\newfile.txt";
if (!File.Exists(path))
{
// This statement ensures that the file is created,
// but the handle is not kept.
using (FileStream fs = File.Create(path)) {}
}

Related

Why is there an second '\' when I get my path

I'm writting a small program and I want to get the path of an txt file.
I get the path, but there is always a second '\' in the output of the string variable.
For example:
string path = #"C:\Test\Test\Test\";
expected output: 'C:\Test\Test\Test\'
Output during debug: 'C:\\Test\\Test\\Test\\'
The same is when I use:
public static readonly string AppRoot = Path.GetDirectoryName(Assembly.GetEntryAssembly().Location);
When I run my app during DEBUG, the txt file can not be opened, because it steps into the IF part.
Code:
public static readonly string AppRoot = Path . GetDirectoryName (Assembly.GetEntryAssembly().Location);
FileStream fs;
StreamReader sr;
string dateiname = "anleitung.txt";
string ausgabe;
string path = Path.Combine(AppRoot, dateiname);
if (!File.Exists(path))
{
MessageBox.Show("Die Datei '" + dateiname + "' existiert nicht!", "Fehler", MessageBoxButtons.OK,MessageBoxIcon.Error);
return;
}
fs = new FileStream(dateiname, FileMode.Open);
sr = new StreamReader(fs);
ausgabe = "";
while (sr.Peek() != -1)
ausgabe += sr.ReadLine() + "\n";
sr.Close();
The txt file is stored in the project folder.
The WinForms APP is written in C# with .Net Framework 4.8
Maybe anyone has an idea.
Thank you in advance.
The IDE will show you that it has escaped the backslashes by displaying the double backslash. However, the string itself does not actually contain double backslashes.
There is further information about how escaping is defined in C# here.
If you were to use other reserved characters you should see escaping in the IDE as you have seen for the double backslash, but not on the string's actual output.
eg:(backslashes) In IDE - C:\\myfolder\\myfile.txt - Actual string output - C:\myfolder\myfile.txt
eg:(single quote) In IDE - "\'varValueWithSingleQuotes\'" - Actual string output - 'varValueWithSingleQuotes'
A backslash in a string is an escape character so that you can include things like \n (a newline) or \t (a tab). If you want to include an actual backslash in the string you need to escape it with another backslash, i.e. \\
So you would write your string as:
string path = "C:\\Test\\Test\\Test\\";
But in your case you are using a verbatim string literal (the #) which treats escape sequences literally. So in that case you do not need to add the additional backslash in your line of code.

Having trouble while adding double quotes to a string that is inside a variable in C#?

I am trying to pass a filepath to xcopy command for copying a folder from one location to another( CodedUI using C#).
While doing the same the problems is, I am trying to add double quotes around the path but it's not taking the correct path format.
Code:
string Path = "Some path to folder location";
// Tried all these solutions
Path = '\"' + Path + '\"';
Path = '\"' + Path + '\"';
Path = string.Format("\"{0}\"", Path );
Expected: ""Some path to folder location""
Actual:"\"Some path to folder location"\"
Please help.
In debugger you will see the backslash.
Sent your output to Console and you will see the result is good.
string Path = "Some path to folder location";
Path = "\"" + Path + "\"";
Console.WriteLine(Path);
From what i understand, you want to see
"Some path to folder location"
when you print it. If so, do:
string path = "\"Some path to folder location\"";
or
string path = "Some path to folder location";
var finalString = string.Format("\"{0}\"", path);
Maybe you should try verbatim strings like #"the\path\to\another\location".
This is the best way to write paths without having to struggle with escape codes.
EDIT:
You can use double quotes in a verbatim string:
#"""the\path\to\another\location"""
If you're trying to preserve two sets of double quotes, try building the string like so:
var path = "hello";
var doubleQuotes = "\"\"";
var sb = new StringBuilder(doubleQuotes)
.Append(path)
.Append(doubleQuotes);
Console.WriteLine(sb.ToString()); // ""hello""
Of course, if you want single quotes you simply swap doubleQuotes for singleQuotes = "\""; and get "hello".
To add double quote, you need to add '\' before ' " '.
Note that : if you are having '\' in path, you have to take care of it like below.
if path is "D:\AmitFolder"
string path = #"D:\AmitFolder";
//Or
path = "D:\\AmitFolder"
string str = "\"" + path + "\"";
Console.WriteLine(str);
here str will be "Some path to folder location"
Output:
as in above line we are adding "\"" string as prefix and "\"" as post fix of the main string.
While storing string values if any double quotes are to be added they need to be escaped using backshlash(\). Single quotes are used for character data. The following code should get the output needed.
Path = string.Format("\"{0}\"", Path);
Also I have created a small fiddle here.

Writing to a text file with a variable for the name

Alright, so my question is; I'm trying to save a file to the C: drive in a folder. Now, I know how to do this for regular files like
using(StreamWriter writer = new SteamWriter("c:\\Folder\\TextFile.txt");
What I've been trying to figure out is how I can make it so that the name of text file is the replaced with a variable so Its more like
using(StreamWriter writer = new SteamWriter("c:\\Folder\\Variablegoeshere.txt");
Is there anyway I can do this?
I apologize for my poor question asking skills.
The StreamWriter constructor, like many other constructors and method calls, takes a string argument. You can pass it any string you like. In your first code sample, you're passing the constructor a "string literal" - an unnamed string variable with a constant value. Instead, you can pass a standard string variable, that you construct beforehand. For instance:
string name = // whatever you like
string path = "c:\\Folder\\" + name + ".txt"; // use '+' to combine strings
using (StreamWriter writer = new SteamWriter(path));
I usually like to use the Path.Combine static method when I concatenate path components. Helps me avoid problems with missing or doubled backslashes:
string path = System.IO.Path.Combine("c:\\Folder", name + ".txt");
And, finally, with the string verbatim modifier, you avoid those ugly double-backslashes, that are otherwise necessary because the backslash is the "escape" character in non-verbatim strings:
string path = System.IO.Path.Combine(#"c:\Folder", name + ".txt");
Here's the Microsoft developer reference page for strings in C#. Worth a read, as is the larger C# language reference.
var inputPath = "c:\\Folder\\TextFile.txt";
var folderPath = Path.GetDirectoryName( inputPath );
using ( var writer = new StreamWriter ( Path.Combine( folderPath, "Variablegoeshere.txt" ) )

How to remove characters in a string?

How to remove the some characters in a string ..
string s="testpage\information.xml"
I need only information.xml how to do that?
System.IO.Path may help you with this since the string contains a file path information. In your case, you may use Path.GetFileName(string path) to get the file name from a string.
Example
string s = #"testpage\information.xml";
string filename = Path.GetFileName(s);
//MessageBox.Show(filename);
Thanks,
I hope you find this helpful :)
Assuming the value that will be in s is always a file path, use the Path class to extract the file name
var filename = Path.GetFileName(s);
File path is of the form
aaaa\bbb\ccc\dddd\information.xml
To retrieve the last string, you can divide your string using the delimiter \
String path = #"aaaa\bbb\ccc\dddd\information.xml";
String a[] = path.Split('\\');
This will give String array as ["aaaa", "bbb", "ccc", "dddd", "information.xml"]
You can retrieve the filename as
String filename = a[a.Length-1];
If it is going to be a file path, then you can use the System.IO.Path class (MSDN) to extract the filename.
string s = "testpage\information.xml"
var filename = Path.GetFilename(s);
If it's always right of the backslash separator then you can use:
if (s.Contains(#"\"))
s= s.Substring(s.IndexOf(#"\") + 1);
Hope this is what you want:
var result=s.Substring(s.LastIndexOf(#"\") + 1);
If you are using file paths, see the Path.GetFileName Method
It will not check whether the file exists or not. So it will be faster.
s = Path.GetFileName(s);
If you need to check whether file exists, use File.Exists class.
Another way is to use String.Split() method
string[] arr = s.Split('\\');
if(arr.Length > 0)
{
s = arr[arr.Length - 1];
}
Another way is to use RegEx
s = Regex.Match(s, #"[^\\]*$").Value;
You can use the following line of codes to get file extension.
string filePath = #"D:\Test\information.xml";
string extention = Path.GetExtension(filePath);
If you need file name alone use,
string filePath = #"D:\Test\information.xml";
string filename = Path.GetFilename(filePath );
Use string.Replcae
string s = #"testpage\information.xml";
s = s.Replace(#"testpage\\",""); // replace 'testpage\' with empty string
You will get Output => s=information.xml
# is need only because you have backslash in your string
For further reading about STRING REPLACE
http://www.dotnetperls.com/replace
http://msdn.microsoft.com/en-us/library/system.string.replace.aspx
In C++ you can do something like this. Basically search for "/" or "\" from right to left of the path and crop the string starting from the first occurance of the delimiter:
string ExtractFileName(const string& strPathFileName)
{
size_t npos;
string strOutput = strPathFileName;
if(strPathFileName.rfind(L'/', npos) || strPathFileName.rfind(L'\\', npos))
{
strOutput = strPathFileName.substr(npos+1);
}
return strOutput;
}

Selecting a specific part of a string C#

I am trying to create a new string, which removes certain characters from an existing string e.g.
string path = "C:\test.txt"
so string "pathminus" will take out the "C:\" e.g.
string pathminus = "test.txt"
Use Path.GetFileName
Eg:
string pathminus = Path.GetFileName(path);
There's so many ways that you can remove the a certain part of a string. These are a couple of ways to do it:
var path = #"C:\test.txt";
var root = #"C:\";
Using string.Remove()
var pathWithoutRoot = path.Remove(0, root.Length);
Console.WriteLine(pathWithoutRoot); // prints test.txt
Using string.Replace()
pathWithoutRoot = path.Replace(root, "");
Console.WriteLine(pathWithoutRoot); // prints test.txt
Using string.Substring()
pathWithoutRoot = path.Substring(root.Length);
Console.WriteLine(pathWithoutRoot); // prints test.txt
Using Path.GetFileName()
pathWithoutRoot = Path.GetFileName(path);
Console.WriteLine(pathWithoutRoot); // prints test.txt
You can also use Regular Expression to find and replace parts of a string, this is a little bit harder though. You can read on MSDN on how to use Regular Expressions in C#.
Here's a complete sample on how to use string.Remove(), string.Replace(), string.Substring(), Path.GetFileName() and Regex.Replace():
using System;
using System.IO;
using System.Text.RegularExpressions;
namespace ConsoleApplication5
{
class Program
{
static void Main(string[] args)
{
var path = #"C:\test.txt";
var root = #"C:\";
var pathWithoutRoot = path.Remove(0, root.Length);
Console.WriteLine(pathWithoutRoot);
pathWithoutRoot = Path.GetFileName(path);
Console.WriteLine(pathWithoutRoot);
pathWithoutRoot = path.Replace(root, "");
Console.WriteLine(pathWithoutRoot);
pathWithoutRoot = path.Substring(root.Length);
Console.WriteLine(pathWithoutRoot);
var pattern = "C:\\\\";
var regex = new Regex(pattern);
pathWithoutRoot = regex.Replace(path, "");
Console.WriteLine(pathWithoutRoot);
}
}
}
It all depends on what you want to do with the string, in this case you might want to remove just C:\ but next time you might want to do other types of operations with the string, maybe remove the tail or such, then the above different methods might help you out.
The string class offers all sorts of ways to do this.
If you want to change "C:\test.txt" to "test.txt" by removing the first three characters:
path.Substring(3);
If you want to remove "C:\" from anywhere in the string:
path.Replace("C:\", "");
Or if you specifically want the filename, regardless of how long the path is:
Path.GetFileName(path);
Depending on your intentions, there are many ways to do it. I prefer using the static class Path.
For this specific example, I would look into the Path Class. For your example, you can just call:
string pathminus = Path.GetFileName(path);
Have you looked at the Substring method?
If the string is actually a file path, use the Path.GetFileName method to get the file name part of it.
path.SubString(path.IndexOf('\'))
You want System.Text.RegularExpressions.Regex but exactly what are you trying do here?
In its simplest form:
[TestMethod]
public void RemoveDriveFromPath()
{
string path = #"C:\test.txt";
Assert.AreEqual("test.txt", System.Text.RegularExpressions.Regex.Replace(path, #"^[A-Z]\:\\", string.Empty));
}
Are you just trying to get the file name of a file without the path?
If so do this instead:
[TestMethod]
public void GetJustFileName()
{
string path = #"C:\test.txt";
var fileInfo = new FileInfo(path);
Assert.AreEqual("test.txt", fileInfo.Name);
}
For more general strings, use the string.Split(inputChar), which takes a character as a parameter and splits the string into a string[] wherever that inputChar is found.
string[] stringArr = path.Split('\\'); // need double \ because \ is an escape character
// you can now concatenate any part of the string array to get what you want.
// in this case, it's just the last piece
string pathminus = stringArr[stringArr.Length-1];

Categories

Resources