如何检查文件是否存在,如果不存在则创建,然后在某些地方将文本附加到文件中?

时间:2016-04-06 18:24:49

标签: c# .net winforms

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
using Newtonsoft.Json;

namespace Youtube_Player
{
    public partial class Authentication : Form
    {
        public static string AuthenticationApplicationDirectory;
        public static string AuthenticationFileName = "Authentication.txt";
        StreamWriter w;
        public static bool formclosed = false;

        static Authentication()
        {
            AuthenticationApplicationDirectory = Path.GetDirectoryName(Application.LocalUserAppDataPath) + "Authentication";
            if (!Directory.Exists(AuthenticationApplicationDirectory))
            {
                Directory.CreateDirectory(AuthenticationApplicationDirectory);
            }
            AuthenticationFileName = Path.Combine(AuthenticationApplicationDirectory, AuthenticationFileName);

            if (!File.Exists(AuthenticationFileName))
                File.Create(AuthenticationFileName);
        }


        public Authentication()
        {
            InitializeComponent();

            cTextBox1.Text = Form1.AuthenticationValues.ApiKey;
            cTextBox2.Text = Form1.AuthenticationValues.UserId;
            cTextBox3.Text = Form1.AuthenticationValues.JsonFileDirectory;

            label1.Visible = false;
            button1.Enabled = false;
            button4.Enabled = false;

            cTextBox2.WaterMarkForeColor = Color.Blue;
            cTextBox3.WaterMarkForeColor = Color.Green;
            cTextBox2.WaterMarkActiveForeColor = Color.Blue;
            cTextBox3.WaterMarkActiveForeColor = Color.Green;
            cTextBox1.ForeColor = Color.Red;
            cTextBox2.ForeColor = Color.Blue;
            cTextBox3.ForeColor = Color.Green;
            cTextBox1.WaterMark = "Enter Api Key";
            cTextBox2.WaterMark = "Enter Email Account";
            cTextBox3.WaterMark = "Browse To The Json File Location";
        }

        private void Authentication_Load(object sender, EventArgs e)
        {

        }

        private void cTextBox1_TextChanged(object sender, EventArgs e)
        {
            if (cTextBox1.Text != "Enter Api Key" && cTextBox1.Text != "")
            {
                button1.Enabled = true;
            }
            else
            {
                button1.Enabled = false;
            }
        }

        private void cTextBox2_TextChanged(object sender, EventArgs e)
        {
            if (cTextBox2.Text != "Enter Email Account" && cTextBox2.Text != "")
            {
                button4.Enabled = true;
            }
            else
            {
                button4.Enabled = false;
            }
        }

        private void cTextBox3_TextChanged(object sender, EventArgs e)
        {
            if (cTextBox3.Text != "Browse To The Json File Location" && cTextBox3.Text != "")
                button6.Enabled = false;

        }

        private void button1_Click(object sender, EventArgs e)
        {
            button1.Text = "Confirmed";
            button1.Enabled = false;
            label1.Text = "Updating Settings File";
            label1.Visible = true;
            if (label1.Visible == true)
            {
                button6.Enabled = false;
                button4.Enabled = false;
                button1.Enabled = false;
            }
            FileInfo fi = new FileInfo(AuthenticationFileName);
            if (fi.Length == 0)
            {
                w = new StreamWriter(AuthenticationFileName, true);
                w.WriteLine("Api" + "=" + cTextBox1.Text);
                w.Close();
            }
            else
            {
                w = new StreamWriter(AuthenticationFileName);
                w.WriteLine("Api" + "=" + cTextBox1.Text);
                w.Close();
            }
            timer1.Start();
        }

        private void button4_Click(object sender, EventArgs e)
        {
            button4.Enabled = false;
            label1.Text = "Updating Settings File";
            label1.Visible = true;
            if (label1.Visible == true)
            {
                button6.Enabled = false;
                button4.Enabled = false;
                button1.Enabled = false;
            }
            w = new StreamWriter(AuthenticationFileName, true);
            w.WriteLine("UserId" + "=" + cTextBox2.Text);
            w.Close();

            timer1.Start();
        }

        private void button6_Click(object sender, EventArgs e)
        {
            OpenFileDialog openFileDialog1 = new OpenFileDialog();
            openFileDialog1.InitialDirectory = "c:\\";
            openFileDialog1.Filter = "Json Files (*.json)|*.json";
            openFileDialog1.FilterIndex = 0;
            openFileDialog1.RestoreDirectory = true;
            openFileDialog1.Multiselect = true;
            if (openFileDialog1.ShowDialog() == DialogResult.OK)
            {
                cTextBox3.BackColor = Color.White;
                cTextBox3.ForeColor = Color.Green;
                cTextBox3.Text = openFileDialog1.FileName;
                label1.Text = "Updating Settings File";
                label1.Visible = true;
                if (label1.Visible == true)
                {
                    button6.Enabled = false;
                    button4.Enabled = false;
                    button1.Enabled = false;
                }
                w = new StreamWriter(AuthenticationFileName, true);
                w.WriteLine("JsonFileDirectory" + "=" + cTextBox3.Text);
                w.Close();

                timer1.Start();
            }
        }

        private void button2_Click(object sender, EventArgs e)
        {
            ResetValues(true);
        }

        int count = 0;
        private void timer1_Tick(object sender, EventArgs e)
        {
            count += 1;
            if (count == 2)
            {
                label1.Visible = false;
                timer1.Stop();
                count = 0;
            }
        }

        private void Authentication_FormClosing(object sender, FormClosingEventArgs e)
        {
            ResetValues(false);
        }

        private void ResetValues(bool DeleteFile)
        {
            cTextBox1.Text = "";
            cTextBox2.Text = "";
            cTextBox3.Text = "";
            button1.Text = "Confirm";
            button4.Text = "Confirm";
            button6.Enabled = true;
            timer1.Stop();
            count = 0;
            if (DeleteFile == true)
            {
                if (File.Exists(AuthenticationFileName))
                    File.Delete(AuthenticationFileName);
            }
            Form1.AuthenticationValues.ApiKey = "";
            Form1.AuthenticationValues.JsonFileDirectory = "";
            Form1.AuthenticationValues.UserId = "";
            if (Form1.AuthenticationValues.AuthenticationMenu.Enabled
                == false && (Form1.lines.Length < 3 && Form1.lines.Length > 0))
                Form1.AuthenticationValues.AuthenticationMenu.Enabled = true;
            formclosed = true;
        }
    }
}

在检查现有文件时,第一个问题出在构造函数中:

if (!File.Exists(AuthenticationFileName))
                File.Create(AuthenticationFileName);

这使文件忙于使用。稍后在我的代码中我试图再次使用该文件写入它时,我发现该文件正被另一个进程使用的异常。

第二个问题是在我尝试写入文件的3个地方。 第一名:

w = new StreamWriter(AuthenticationFileName, true);
w.WriteLine("Api" + "=" + cTextBox1.Text);
w.Close();

然后在代码中的另一个地方,我再次写入文件:

w = new StreamWriter(AuthenticationFileName, true);
w.WriteLine("UserId" + "=" + cTextBox2.Text);
w.Close();

最后:

w = new StreamWriter(AuthenticationFileName, true);
w.WriteLine("JsonFileDirectory" + "=" + cTextBox3.Text);
w.Close();

问题首先是文件正忙于使用,因为检查是否存在我在构造函数中进行的操作。

第二个问题是,我希望如果在文件中没有以&#34; Api&#34;开头的行。然后写下Api部分:

w.WriteLine("Api" + "=" + cTextBox1.Text);

但是如果它确实存在并且在textBox cTextBox1.Text中更改了文本我想要将更改的文本写入文件到Api行所在的位置。并附加一条新的Api线。

对于我写入文件的所有其他两个地方也是如此。 如果我将它全部弄错,不要在写入时appen,它将每次写一行并覆盖该行。 但是,如果我做的是真的,它会附加许多Api线或许多UserId线。 我希望每个人都有时间用textBox替换该行,只在这一行覆盖,但是用新文本覆盖。

如果在cTextBox1中有文本:Hello World 然后我改为:Hello World Now 然后用Hello World Now替换Api行Hello World

1 个答案:

答案 0 :(得分:1)

好的,解决你的主要问题:

File.CreateFile实际上会打开一个文件流供您使用。最简单的解决方法是使用File.CreateFile()。关闭()以在完成后关闭它。

接下来,您正在尝试更改文件中的数据,但您从未读过它以查找信息。

您可以查找StreamReader并使用它,并解析数据并找出其中的位置,但有一个更明显的选择:每次都重写所有信息。