- Home /
Create Text file and open - write on it after button click
Hello there. My code is like that;
void Start () {
StreamWriter sr = File.CreateText(FILE_NAME);
sr.Close();
}
void Update () {
if (Input.GetMouseButtonDown (0) && EventSystem.current.currentSelectedGameObject == button1)
{
StreamWriter sr = File.OpenWrite (FILE_NAME);
sr.WriteLine ("You clicked on first button.");
sr.Close();
}
else if (Input.GetMouseButtonDown (0) && EventSystem.current.currentSelectedGameObject == button2)
{
StreamWriter sr = File.OpenWrite (FILE_NAME);
sr.WriteLine ("You clicked on second button.");
sr.Close();
}
}
My aim is basic actually. When I clicked on button it should be written on a Text file. I think I have a problem about opening and closing of text file. Because I got 'Cannot implicitly convert type "System.IO.FileStream' to 'System.IO.StreamWriter' " error.
What should I do now? Thanks in advance.
Answer by Reynarz · Jul 23, 2017 at 02:19 PM
Maybe this can help you.
var file = File.Open("File_Name", FileMode.OpenOrCreate, FileAccess.ReadWrite);
var writer = new StreamWriter(file);
var reader = new StreamReader(file);
Or the simple way:
var textFile = File.ReadAllText("C:/Filename.txt");
File.WriteAllText("C:/Filename.txt", textFile + "Hello");
$$anonymous$$y bad but how can I convert "var file,write,reader" to C#?
That code is C# already "var keyword" is meaning of: "I will figure out what type is in the right hand". But you can put the value type explicit:
FileStream file = File.Open("File_Name", File$$anonymous$$ode.OpenOrCreate, FileAccess.ReadWrite);
StreamWriter writer = new StreamWriter(file);
StreamReader reader = new StreamReader(file);
Ok it works, but the main problem still exists. When I create a text file in "void Start()", I can't use the same file in "void Update()". It still gives the error :(
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
Where can I view the code created by the editor? 1 Answer
How do i use StateMachine logic with my code ? 1 Answer
Problem with saving List of objects !!! 2 Answers