How to rename a file with string format in C#? - c#

This is the situation:
I created a new file name using the string format like:
string newFileName = string.Format("{0}/{1}/{2}/{3}.txt", FileInfo.Year,
FileInfo.Month, FileInfo.Day, FileInfo.Time);
and I have another(old) file with a path: string path = #"C:\Users\Public\fileName.txt"
I would like to change or move the old --> the new. How to do that? Is it possible to change the path of the new?
Is there anyone who can help me. Thanks in advance

string path = #"C:\Users\Public\fileName.txt";
if (File.Exists(path))
File.Move(path, "DestinationFilePath");

Related

How to get file name from a path in c#

I want to extract the filename from a file path in C#.
For example:
textBox1.Text = "C:\Users\Elias\Desktop\image.png"
I want to copy the file name: "image.png" to the textBox2
How can i do that?
Use the static Path.GetFileName method in System.IO:
Path.GetFileName(#"C:\Users\Elias\Desktop\image.png"); // --> image.png
regarding your example:
textBox2.Text = Path.GetFileName(textBox1.Text);
System.IO.FileInfo class can help with parsing that information:
textBox2.Text = new FileInfo(textBox1.Text).Name;
MSDN documentation on the FileInfo class:
https://msdn.microsoft.com/en-us/library/system.io.fileinfo(v=vs.110).aspx

Regex to get whatever the parent directory of my file is in string file path

I have a string file path and I am looking to get the name of the folder that is next up from the file.
Here is my file path:
Test/FilePathNeeded/testing.txt
I am sure there is a way to get FilePathNeeded from the file path above with regex, I just am not sure how it would be done. My thought is that the amount of directories that testing.txt is in should not matter, but the folder needed would always be one up from the file.
I hope this makes sense. Please let me know if it doesn't. Would anyone be able to help?
Without Regex, You can use:
string directory = new DirectoryInfo(
Path.GetDirectoryName("Test/FilePathNeeded/testing.txt")
).Name;
Path.GetDirectoryName will return Test/FilePathNeeded that you can use in the constructor of DirectoryInfo and get Name.
Another option is to use Directory.GetParent like:
var directory = Directory.GetParent("Test/FilePathNeeded/testing.txt").Name;
Simply use:
var dir = new FileInfo("Test/FilePathNeeded/testing.txt").Directory.Name;
This will return FilePathNeeded
Use the FileInfo class:
var fileInfo = new FileInfo(#"Test/FilePathNeeded/testing.txt");
var directoryInfo = fileInfo.Directory;
var parentDirectoryName = directoryInfo.Name;

Create a copy of a file in same location as original

The end-user supplies a path, indicating where the original document is.
string DocxFileName = "C:\\WorksArshad\\3.docx";
I'd like to create a copy of the document name 3.docx as 3Version1.docx and store the copy in the same directory as the original.
How do I get the whole path without the file name and extension?
(i.e.) I need to get the "C:\\WorksArshad\\" path alone.
FileInfo file = new FileInfo(Session.FileName);
string path = file.Directory.tostring();
and then using
string fileName = Path.GetFileNameWithoutExtension(Session.FileName);
string DocxFileNamee = path + "\\" + fileName + "V1.docx";
File.Copy(Session.FileName, DocxFileNamee, true);
where in Session.FileName = "C:\WorksArshad\3.docx" and in path I'd get "C:\WorksArshad"
requirement solved .
Or
File.Copy(Session.FileName, Path.Combine(Path.GetDirectoryName(Session.FileName)
, Path.GetFileNameWithoutExtension(Session.FileName)+"V1.docx"),true);
both the above gives the solution

URI formats are not supported in c#

I am trying to insert my data in to xml file. the xml file location
path: http://AutoCompleteInGridView%20new1/Design/Pro/pricelist.xml.
when inserting my data i got error URI formats are not supported.
It shows argument exception was unhandled.I want to save my xml
file in server system.these url belongs to ServerPath location.
can anyone give me a suggestion or links to solve these problem.
here is the error:
Use this sample:
string uriPath = "YourAddress/pricelist.xml";
string localPath = new Uri(uriPath).LocalPath;
Try like this:
string SavePathUrl = ConfigurationManager.AppSettings["SavePathUrl"];
string strFileName = DateTime.Now.ToString("dd-mmm-yyyy-hh-mm-ss-ffffff") + "^" + fileName;
File.WriteAllBytes(new Uri(SavePathUrl).AbsoluteUri + strFileName, Convert.FromBase64String(base64String));
return strFileName;
you could try with this solution:
http://social.msdn.microsoft.com/Forums/en-US/eccd585a-ac2b-4700-aa28-abb4802cd3a5/uri-formats-are-not-supported-error-with-xmlsave?forum=xmlandnetfx
Basically, use
doc.Save(Server.MapPath("~/EEPPriceList/Products.xml"))

Change File Extension Using C#

I have many file types: pdf, tiff, jpeg, bmp. etc.
My question is how can I change file extension?
I tried this:
my file= c:/my documents/my images/cars/a.jpg;
string extension = Path.GetExtension(myffile);
myfile.replace(extension,".Jpeg");
No matter what type of file it is, the format I specify must be with the file name. But it does not work. I get file path from browser like c:\..\..\a.jpg, and the file format is a.jpeg. So, when I try to delete it, it gives me an error: Cannot find the file on specified path'. So, I am thinking it has something to do with the file extension that does not match. So, I am trying to convert .jpg to .jpeg and delete the file then.
There is: Path.ChangeExtension method. E.g.:
var result = Path.ChangeExtension(myffile, ".jpg");
In the case if you also want to physically change the extension, you could use File.Move method:
File.Move(myffile, Path.ChangeExtension(myffile, ".jpg"));
You should do a move of the file to rename it. In your example code you are only changing the string, not the file:
myfile= "c:/my documents/my images/cars/a.jpg";
string extension = Path.GetExtension(myffile);
myfile.replace(extension,".Jpeg");
you are only changing myfile (which is a string). To move the actual file, you should do
FileInfo f = new FileInfo(myfile);
f.MoveTo(Path.ChangeExtension(myfile, ".Jpeg"));
See FileInfo.MoveTo
try this.
filename = Path.ChangeExtension(".blah")
in you Case:
myfile= c:/my documents/my images/cars/a.jpg;
string extension = Path.GetExtension(myffile);
filename = Path.ChangeExtension(myfile,".blah")
You should look this post too:
http://msdn.microsoft.com/en-us/library/system.io.path.changeextension.aspx
The method GetFileNameWithoutExtension, as the name implies, does not return the extension on the file. In your case, it would only return "a". You want to append your ".Jpeg" to that result. However, at a different level, this seems strange, as image files have different metadata and cannot be converted so easily.
Convert file format to png
string newfilename ,
string filename = "~/Photo/" + lbl_ImgPath.Text.ToString();/*get filename from specific path where we store image*/
string newfilename = Path.ChangeExtension(filename, ".png");/*Convert file format from jpg to png*/
Alternative to using Path.ChangeExtension
string ChangeFileExtension(ReadOnlySpan<char> path, ReadOnlySpan<char> extension)
{
var lastPeriod = path.LastIndexOf('.');
return string.Concat(path[..lastPeriod], extension);
}
string myfile= #"C:/my documents/my images/cars/a.jpg";
string changedFileExtesion = ChangeFileExtension(myfile, ".jpeg");
Console.WriteLine(changedFileExtesion);
// output: C:/my documents/my images/cars/a.jpeg

Categories