Appending Text to a file path - c#

This is probably a simple question, I'm writing a WinForms C# application in VS 2012. I was wondering if there a way to add an extension such as .csv to some writing in a textbox. Say the user wrote in C:\Users\Desktop\filename but left out the .csv part of the path. Is there any way to add the .csv after an execute button is clicked?
Any help would be much appreciated.

You can use Path.ChangeExtension.
// Nota bene: Path.ChangeExtension does not change textBox1.Text directly (or any
// argument given), you MUST use the result if you care about it.
string newPath = Path.ChangeExtension(textBox1.Text, "csv");
The period is optional, and the filename component need not include an extension.
As a future reference, if you can think of something you need to do with a path to a file or a directory...it exists in System.IO.Path. Rare for there not to be support for a common task in that class.

If you do not want to change a valid extension in the string, you could do it like this instead:
// first test for an extension
if(!Path.HasExtension(textBox1.Text.Trim()))
{
// then add on '.csv' if one does not exist
string path = Path.ChangeExtension(textBox1.Text.Trim(), ".csv");
// ... use path ...
}

Related

Correct filepath to read from file

I want to read from a file. But i do not how to alter to the correct filepath.
I just want to read from a file called Level.txt. If I do; string path = "Level.txt".
The program tries to search it from; C:\...\ProjIV\ProjIV\bin\x86\debug\Level.txt.
When I want the damn thing in: C:\...\ProjIV\ProjIV\ProjIVContent\Level.txt.
Skip the second question. As someone else said, one question at the time. Also; solved.
If you just provide a path like that, your program will search in the running (working) directory that it is executing in. You can provide an explicit path:
C:\<whatever you need here>\ProjIV\ProjIV\ProjIVContent\Level.txt
Or a relative path:
..\..\..\..\ProjIVContent\Level.txt
That's pretty ugly though, I'd stick with the first one. Or move Level.txt into your working directory.

How to retrieve the full name of a file when passing it a parameter to a C# program

I am writing a utility that edits .docx files. I've made it so that when the user right clicks on the correct type of file, it automatically makes the changes and saves the document with a bit of text appended to the file name. All of this works great, except for the fact that I am receiving heavily truncated file names. If the file name contains more than one word, the string passed to the program is has most of its characters replaced by a single ~. Is there any way to either read the original file name, or have the parameter be the full string?
I found the solution to what I was trying to do. I ended up using the C# method Path.GetFullPath.
string path = Path.GetFullPath(originalpath);
This outputs the full file name as opposed to the truncated one.
http://msdn.microsoft.com/en-us/library/system.io.path.getfullpath.aspx
File.getCanonicalPath will give you what you want
http://msdn.microsoft.com/en-us/library/aa988183(v=vs.80).aspx
Put the whole path between two double quot; like:
var fn = "\"C:\\Path With Spaces And Special Characters\\#\\to\\My File.docx\"";
// send fn as an argument to the other process

Inserting a Line at a specific place in a txt using .net

The process I currently use to insert a string into a text file is to read the file and modify it as I write the file out again which seems to be how everyone is doing it.
Since .net has such a diverse library I was wondering if there was a specific command for inserting a string at a specific line in a txt file.
I would imagine it would look something like this:
dim file as file
file.open("filePath")
file.insert(string, location) 'this isn't actually an option, I tried
No, there's nothing specifically to do that in .NET.
You can do it very simply if you're happy to read all the lines of text in:
var lines = File.ReadAllLines("file.txt").ToList();
lines.Insert(location, text);
File.WriteAllLines("file.txt", lines);
It would be more efficient in terms of memory to write code to copy a line at a time, inserting the new line at the right point while you copy, but that would be more work. If you know your file will be small, I'd go for the above.
You could simply read all the text into a string, then use the string insert method, e.g.
File.WriteAllText("file.txt", File.ReadAllText("file.txt").Insert(startIndex, "value"));

How to get filename from a file "template.docx.amp" in c#?

I have got a strange template whose extension is ".docx.amp" . Now i want to get fileName. i.e "template". Path.GetFileNameWithoutExtension() fails as it returns template.docx. Is there any other built in mechanism or i will have to go the ugle string comparison/split way. Please suggest and give some workaround
Nope, you will have to use some kind of string split, eg:
var nameWithoutExtension = filename.Split('.')[0];

Is there a more correct type for passing in the file path and file name to a method

What I mean by this question is, when you need to store or pass a URL around, using a string is probably a bad practice, and a better approach would be to use a URI type. However it is so easy to make complex things more complex and bloated.
So if I am going to be writing to a file on disk, do I pass it a string, as the file name and file path, or is there a better type that will be better suited to the requirement?
This code seems to be clunky, and error prone? I would also need to do a whole bit of checking if it is a valid file name, if the string contains data and the list goes on.
private void SaveFile(string fileNameAndPath)
{
//The normal stuff to save the file
}
A string is fine for the filename. The .Net Framework uses strings for filenames, that seems fine.
To validate the filename you could try and use a regular expression or check for invalid characters against System.IO.Path.GetInvalidFileNameChars. However, it is probably easier to handle the exceptional cases of invalid filenames by handling the exception that will occur when you try and create the file - plus you need to do this anyway....
Unfortunate as it is, string is the idiomatic way of doing this in .NET - if you look at things like FileStream constructors etc, they use strings.
You could consider using FileInfo (or DirectoryInfo) but that would be somewhat unusual.
You could use FileInfo (from System.IO) to pass it around, but strings are more or less standard when referring to files.
You could always use Path.GetFileName({yourstring}) to get the filename from the path.
String is fine, but you should put in some effort to ensure that the file is being saved into the directory you expect.
If you're working with a filepath a string is usual.
If you're working with a URL you could consider using the System.Uri class e.g.
Uri myUri = new Uri(myUrl, UriKind.Absolute);
This will allow you to work with properties such as uri.Host, uri.Absolute path etc. It will also give you a string array (Segments) for the separate subfolders in the url.
MSDN info here: System.Uri

Categories