locked
How can I write to a text file each time clicking a button and overwrite the content in the file ? RRS feed

  • Question

  • I tried:

    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.IO;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    using System.Windows.Forms;
    
    namespace WindowsFormsApp1
    {
    	public partial class Form1 : Form
    	{
    		public Form1()
    		{
    			InitializeComponent();
    		}
    
    		private void button1_Click(object sender, EventArgs e)
    		{
    			using (StreamWriter w = new StreamWriter(@"d:\test\names.txt", true))
    			{
    				for (int i = 0; i < 10; i++)
    				{
    					string test = i + "Name";
    					w.WriteLine(test + Environment.NewLine);
    				}
    			}
    		}
    	}
    }
    

    But this will add new files to the file each time I click the button.

    But if I set it to false then it will write one line and will overwrite the line and will not write all the lines.

    Tried also: 

    using (StreamWriter w = File.AppendText(@"d:\test\names.txt"))

    But again it's adding more lines even if they are exist already in the text file.

    I want that each time I click the button to create new empty text file and write all the lines to it.

    My original code is in csharp unity script:

    using System;
    using System.Collections;
    using System.Collections.Generic;
    using System.IO;
    using System.Linq;
    using System.Reflection;
    using UnityEditor;
    using UnityEditor.Animations;
    using UnityEngine;
    
    public class Manager : EditorWindow
    {
        private static Manager editor;
        private static int width = 350;
        private static int height = 300;
        private static int x = 0;
        private static int y = 0;
        private static List<string> allFiles = new List<string>();
    
        [MenuItem("Window/Manager")]
        static void ShowEditor()
        {
            editor = EditorWindow.GetWindow<Manager>();
            CenterWindow();
        }
    
        private void OnGUI()
        {
            if (GUILayout.Button("Rename"))
            {
                Rename();
            }
        }
    
        public void Rename()
        {
            DirSearch();
    
            if (allFiles.Count > 0)
            {
                for (int i = 0; i < allFiles.Count; i++)
                {
                    int idx = allFiles[i].IndexOf("Assets");
                    string filename = Path.GetFileName(allFiles[i]);
                    string asset = allFiles[i].Substring(idx);
                    AnimationClip orgClip = (AnimationClip)AssetDatabase.LoadAssetAtPath(
                         asset, typeof(AnimationClip));
    
                    var fileName = Path.GetFileNameWithoutExtension(allFiles[i]);
                    var importer = (ModelImporter)AssetImporter.GetAtPath(asset);
    
                    RenameAndImport(importer, fileName);
                }
            }
        }
    
        private void RenameAndImport(ModelImporter asset, string name)
        {
            ModelImporter modelImporter = asset as ModelImporter;
            ModelImporterClipAnimation[] clipAnimations = modelImporter.defaultClipAnimations;
    
            using (StreamWriter w = File.AppendText(@"d:\test\names.txt"))
            {
                for (int i = 0; i < clipAnimations.Length; i++)
                {
                    clipAnimations[i].name = "magic_" + name;
                    string n = clipAnimations[i].name; // no need to append Environment.NewLine
                    w.WriteLine(n);
                }
            }
    
            modelImporter.clipAnimations = clipAnimations;
            modelImporter.SaveAndReimport();
        }
    
        private static void CenterWindow()
        {
            editor = EditorWindow.GetWindow<Manager>();
            x = (Screen.currentResolution.width - width) / 2;
            y = (Screen.currentResolution.height - height) / 2;
            editor.position = new Rect(x, y, width, height);
            editor.maxSize = new Vector2(width, height);
            editor.minSize = editor.maxSize;
        }
    
        static void DirSearch()
        {
            string info = Application.dataPath + "/Mixamo/Animations/medea_m_arrebola/Magic Pack";
            string[] fileInfo = Directory.GetFiles(info, "*.fbx", SearchOption.AllDirectories);
            foreach (string file in fileInfo)
            {
                if (file.EndsWith(".fbx"))
                    allFiles.Add(file);
            }
        }
    }

    The idea is the same as the above winforms code.

    Inside OnGUI I have a button called "Rename" and I want that each time I click the button create new text empty file and write all the lines in the loop to the file. And don't append or add over again the lines.

    Thursday, January 3, 2019 9:31 PM

Answers

  • To overwrite and be more efficient with the actual writing I recommend using StringBuilder.

    using System;
    using System.IO;
    using System.Text;
    using System.Windows.Forms;
    
    namespace WindowsFormsApp1
    {
        public partial class Form1 : Form
        {
            public Form1()
            {
                InitializeComponent();
            }
    
            private void button1_Click(object sender, EventArgs e)
            {
                var fileName = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, 
                    "names.txt");
    
                var sb = new StringBuilder();
                for (int index = 0; index < 10; index++)
                {
                    sb.AppendLine(index.ToString() + "Name");
                }
                File.WriteAllText(fileName,sb.ToString());
            }
        }
    }

    This results are after three clicks 

    This (which is essentially the same as your's works fine for me)

    var fileName = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "names.txt");
    using (var writer = new StreamWriter(fileName))
    {
        for (int index = 0; index < 10; index++)
        {
            writer.WriteLine(index.ToString() + "Name");
        }
    }

    One more twist, create the file first.

    var fileName = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "names.txt");
    
    File.Create(fileName).Dispose();
    
    using (var writer = new StreamWriter(fileName))
    {
        for (int index = 0; index < 10; index++)
        {
            writer.WriteLine(index.ToString() + "Name..");
        }
    }


    Please remember to mark the replies as answers if they help and unmark them if they provide no help, this will help others who are looking for solutions to the same or similar problem. Contact via my Twitter (Karen Payne) or Facebook (Karen Payne) via my MSDN profile but will not answer coding question on either.
    VB Forums - moderator
    profile for Karen Payne on Stack Exchange, a network of free, community-driven Q&A sites




    Friday, January 4, 2019 12:18 AM