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
Related
I am trying to append text to a text file, but I can't find anywhere how to actually locate an existing file.
partial void MainBtn_TouchUpInside(UIButton sender)
{
var Pp = ("Selected Form Of Exchange: Paypal");
string mydocpath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments(WHAT DO I WRITE IN THIS SPACE??);
using (StreamWriter outputFile = new **StreamWriter(Path.Combine(mydocpath, "SelectPayment.txt")))
//I know that the file already exists, I just am trying different things.
{
outputFile.WriteLine(Pp);
}
So what do I do? Thanks
Josh
you specify a file by combining a folder path and a file name to create a file path
// this returns the path to a folder
string path = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments));
// combine that with a file name to create a file path
string file = Path.Combine(path, "myFile.text");
// append text to file
File.AppendAllText(file, "this is the text I want to append);
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
I am trying to copy a file (.docx, .pdf, .pptx etc) from a source folder(on server) to a destination folder(on client).
The user can choose which among the list of files that he wants to download. He selects the files and then downloads it(Copies it to his computer) to the destination path
dstnLocation= #"C:\Fldr\Docs;
My Code:
string sourceLocation = textBox2.Text;
string dstnLocation = #"C:\Fldr\Docs";
System.IO.FileInfo file = new System.IO.FileInfo(dstnLocation);
file.Directory.Create();
System.IO.File.Copy(sourceLocation, dstnLocation,true);
MessageBox.Show("Download Complete");
The problem is that it creates a file as "Docs"(where one has to use open with to open the file) and if I am not wrong then its because of the destination path. Could someone please tell what all am I doing wrong.
The source path is retrieved through database!
you need to concat otherwise you're destination location is just the folder not the file path destination
so do something like
var destFile = string.Format(#"{0}\{1}", dstnLocation, Path.GetFileName(sourceLocation));
then copy that
So code becomes
string sourceLocation = textBox2.Text;
string dstnLocation = string.Format(#"C:\Fldr\Docs\{0}", Path.GetFileName(sourceLocation);
if (! System.IO.Directory.Exists(dstnLocation))
{
System.IO.Directory.CreateDirectory(dstnLocation);
}
System.IO.File.Copy(sourceLocation, dstnLocation,true);
MessageBox.Show("Download Complete");
You are creating the file name incorrectly:
string dstnLocation = #"C:\Fldr\Docs";
System.IO.FileInfo file = new System.IO.FileInfo(dstnLocation);
This creates a file with the name "C:\Fldr\Docs" for example what you want is "C:\Fldr\Docs\myfilename.docx" if I am not mistaken?
Try this instead:
var filename = Path.GetFileName(sourceLocation);
string dstnLocation = Path.Combine(#"C:\Fldr\Docs", filename);
The problem here is that the destination requires an "output" file name.
This problem lies in this line of code
System.IO.File.Copy(sourceLocation, dstnLocation,true);
The dstnLocation needs to be concatenated with the output file name for example:
System.IO.File.Copy(sourceLocation, Path.Combine(dstnLocation,"Database.dbs"),true);
I have an issue with the reading a file in C#
I have two different locations for .exe (both different) and reading the same .xml file. So when I give the path like this:
TextReader textReader = new StreamReader(#"../../../TrajectoryGen/obstacleList.xml");
it is able to read from one location ( which is 3 folders behind as used in the path) but not from another location (which is only 2 folders behind)
How do I fix this problem so that it works from both folders?
First way, this relies on you knowing one of the parent folder's names.
const string FILENAME = "obstacleList.xml";
const string FOLDER = "TrajectoryGen";
string path = Path.GetFullPath(System.Reflection.Assembly.GetExecutingAssembly().Location);
do
{
path = Path.GetDirectoryName(path);
} while (!Path.GetFileName(path).Equals(FOLDER, StringComparison.OrdinalIgnoreCase));
string filepath = String.Format("{0}{1}{2}", path, Path.DirectorySeparatorChar, FILENAME);
^^ You can also use a partial path in the FILENAME like the example below incase you need to into directories once you are at your "base" folder that you know the name of.
Second way blindly continues up directories
const string FILENAME = #"TrajectoryGen\obstacleList.xml";
string path = Path.GetFullPath(System.Reflection.Assembly.GetExecutingAssembly().Location);
string filepath;
do
{
path = Path.GetDirectoryName(path);
//pump
filepath = String.Format("{0}{1}{2}", path, Path.DirectorySeparatorChar, FILENAME);
} while (!File.Exists(filepath));
Both require "using System.IO;" and both have no error handling implemented and will throw NullReferenceException if the file/folder is not found.
I purposely used the do-while loop because the definition of path will included the executable name.
I have the code below and I get the result like this
C:\\Users\\Administrator\\Projects\\CA\\Libraries\\ConvertApi-DotNet\\Example\\word2pdf-console\\bin\\Release\\\\..\\..\\..\\..\\test-files\\test.docx
The file is found but I would like to show user this path and the formating is not user friendly. I would like to get
C:\\Users\\Administrator\\Projects\\CA\\Libraries\\test-files\\test.docx
I have tried to use Path.Combine but it do not work.
var baseDirectory = AppDomain.CurrentDomain.BaseDirectory;
string inFile = baseDirectory + #"\..\..\..\..\test-files\test.docx";
You could use a combination of Path.Combine and Path.GetFullPath:
var baseDirectory = AppDomain.CurrentDomain.BaseDirectory;
var file = #"..\..\..\..\test-files\test.docx";
string inFile = Path.GetFullPath(Path.Combine(baseDirectory, file));
Description
You say that the file is found.
Then you can use FileInfo (namespace System.IO) for that.
Sample
FileInfo f = new FileInfo(fileName);
f.Exists // Gets a value indicating whether a file exists.
f.DirectoryName // Gets a string representing the directory's full path.
f.FullName // Gets the full path of the directory or file.
More Information
MSDN - FileInfo Class