Saving user inputs to an existing text file in ASP.NET MVC - c#

How would I go about saving a user form input from a view to an existing text file with the ASP.NET MVC framework?

So to start of, you would accept some code from the user and then save it:
string userInput =Console.Readline();
Then you would use the code WriteAllText(). This allows you to create a new file and writes the contents to it. If the file already exists, it will be overwritten.
So basically:
string userInput =Console.Readline();
File.WriteAllText("thenameyouwanttogivetoyourfile.txt", userInput);
This reads the file and then outputs it
string readText = File.ReadAllText("thenameyouwanttogivetoyourfile.txt");
Console.WriteLine(readText);
Thats how you create a new file. To overwrite a file that already exists, you do the same thing but with the keyword Create(). This creates or overwrites a file and if you want to replace the contents of one file with another, use Replace().
For futher help try this link:
https://learn.microsoft.com/en-us/dotnet/api/system.io.file?view=netframework-4.8

Related

Open, remove text, and save a text file

I want to edit some text files automatically, but I don't know what to used to do it.
I want to open a file, check all lines, if one line begins with a 'C', I remove first 39-characters, etc .. then save all the file with an other name.
I already have a portion of code :
var car = ligne[0];
if(car != 'C') { continue; }
ligne.Remove(0, 39);
I use StreamReader to read, but what is the simple way to read and save in another file ?
Try File.ReadAllLines, which opens a file, reads everything, closes the file and returns an array containing all lines.
Do your processing....
Then File.WriteAllLines to open a file, write data, and close the file.

How to append to a file after File.CreateText?

I am writing a C# app that needs to create a CSV file.
The problem is after issuing a File.CreateText({file path}), I cannot immediately write to it. If the file already exists, I can write no problem. Here is the code:
if (!File.Exists(file_name))
{
File.CreateText(file_name);
File.WriteAllText(file_name, String.Format("Old Name,Short Name{0}", this.old_name_txt.Text, this.new_name_txt.Text, Environment.NewLine));
}
else
{
File.AppendAllText(file_name, String.Format("{0},{1}{2}", this.old_name_txt.Text, this.new_name_txt.Text, Environment.NewLine));
}
After creating the file, I have also tried "File.AppendAllText..."
The error it is producing says that it cannot write because the file is being used by another process.
File.CreateText will create a text file and open the file. It then returns a StreamWriter which you could use to access that created file. Because you opened the file like this already, you will get an error when trying to open that file again.
When reading the docs for File.CreateText make sure to look at the return value as well, to understand what the function does.
Please read the documentation for File.AppendAllText as well and then change your code accordingly.
Here's the most important part in the docs:
AppendAllText(String, String)
Description
Opens a file, appends the specified string to the file, and then closes the file. If the file does not exist, this method creates a file, writes the specified string to the file, then closes the file.
You should be able to solve your problem by yourself now.

Open a file without dialog

with openFileDialog you would select a file and after pressing "OPEN" it would paste the filepath of the selected file (c:\blob\template) into an textbox.
I would like to do automatically select the file c:\blob\template en then put the filepath in the textbox. basically the exact same thing as openfiledialog without a dialog. i have been trying to do this for some time now. can somebody help me out with this? i have no clue how to realise this.
i`m only able to get the filepath and paste the string in the textbox but this but only fills the box with a string. i need to load the file/template in there.
private void txt()
{
string fileName = "template";
string fullPath;
fullPath = Path.GetFullPath(fileName);
lblFirstTemplate.Text = fullPath;
}
Thank you in advance!
The code you now have will only get the file path. What you need to add is code that will actually open the file and read its content.
Let's say your file contains some text. You can use the following line to read the complete file as text:
System.IO.File.ReadAllText(fullPath);
If your file contains some other data like binary data, you can use:
System.IO.File.ReadAllBytes(fullPath);
And instead of reading all data at once, you can read it one line or a couple of bytes at a time. A good place in the documentation to start is: Common I/O Tasks

Load from text file at program startup

Sorry for the likely noobish question, just starting to learn c#, and couldn't find anything that worked.
I'm making a text editor in c#, and so far it can open and save text files from inside the program with dialogs, but how can I make it load the text from a file that I open in windows explorer, outside of the editor, with the editor
Basically, I can already read from text files opened inside the editor, but how can i make it so that if I open a text file (and have the default program for opening text files set to my editor), it'll read it?
I saw something about getting the filename somehow and passing it as an argument, if that helps.
If I understood you correctly, you want to pass the filename/names as command line arguments ?
If you look at the Main, which starts the program you can see that it will store parameters in a string[] (string array) so if you pass arguments you can just check the args[] inside the program to get the parameters you sent in. Please ask more if you need more help !
UPDATED
As per your request if you open a file from windows explorer it will send the path of the file it to the Main method. So lets say you right click a file and choose to open it with your text editor. You have to use the path as I do below, and read the file's content. Then you can do whatever you want with the content.
class TestClass {
static void Main(string[] args) {
// Now you have all arguments in the string array
if (args.Length != 0) {
string pathToTextfile = args[0];
}
StreamReader textFile = new StreamReader(pathToTextfile);
string fileContents = textFile.ReadToEnd();
textFile.Close();
}
}
So you have a text editor coded in C#, and you want to be able to open a text file through double clicking on the file in Windows explorer. If so, basically 2 steps:
1. Your editor program must accept one argument as the file name. Carl had already given an example.
2. You need to associate *.txt files with your text editor. This could be done through editing Windows registry. please check What registry keys are responsible for file extension association
You can use the OpenFileDialog class to select a file to show in your program.

Unique File Renaming Issue

I am developing an app right now that reads in data from a windows from and generates an XML file based on the input.
I am tasked with creating a new file each time the form is updated (User presses "Submit"). (so far so good)
Here is the catch: The file has to be named after a prominent field input. (If the user types '993388CX' in the text box, the app would rename the pending file 993388CX.xml).
I understand how to actually rename a file in C#, but not how to rename it based on a form's input. Do any classes/methods exist that will dynamically rename the file based on the form input?
Code:
//Reads info1 from user input on the app UI and generates XML statement
XTemp = XDoc.CreateElement("New_Info");
XTemp.InnerText = info1.Text;
Xsource.AppendChild(XTemp);
XDoc.Save(#"C:\oldfile.xml");
I need the new file to be renamed after the string in info1.Text
If the user input was "John5", the file needs renamed to john5.xml
Thank you
Either directly save it with the correct name:
XDoc.Save(String.Format("C:\\{0}.xml",info1.Text));
OR
Rename it afterwards
File.Move("c:\\oldfile.xml", String.Format("C:\\{0}.xml",info1.Text));
XDoc.Save(#"C:\" + info1.Text + ".xml");
File.Move should do what you want.

Categories