Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/327.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何更改txt文件中的值并覆盖它_C#_File_Text_Overwrite - Fatal编程技术网

C# 如何更改txt文件中的值并覆盖它

C# 如何更改txt文件中的值并覆盖它,c#,file,text,overwrite,C#,File,Text,Overwrite,我创建了*.txt文件,其中包含如下数据: deviceid,model,availability,renterID,renterName,reneterSurname,OS 0001,iPhone_5S,false,002,John,Dowland,iOS-7.1.2 0002,GalaxyS3,false,002,Amadeus,Mozart,Android-4.3.2 在我的C#应用程序(WPF应用程序)中,获得了对文件进行操作的函数: private void rentSaveButt

我创建了*.txt文件,其中包含如下数据:

deviceid,model,availability,renterID,renterName,reneterSurname,OS
0001,iPhone_5S,false,002,John,Dowland,iOS-7.1.2
0002,GalaxyS3,false,002,Amadeus,Mozart,Android-4.3.2
在我的C#应用程序(WPF应用程序)中,获得了对文件进行操作的函数:

private void rentSaveButton_Click(object sender, RoutedEventArgs e)
    {
        StreamWriter sw = new StreamWriter(@"D:\deviceLib.txt", true);

        var currentUser = _list.Where(u => u.Id == int.Parse(userIDTextBox.Text)).FirstOrDefault();

        var currentDevice = _list2.Where(i => i.deviceId == int.Parse(deviceIDTextBox.Text)).FirstOrDefault();
        if (currentDevice != null &&  currentUser != null)
        {
            currentDevice.Availability = false;
            currentDevice.rentId = currentUser.Id;
            currentDevice.rentName = currentUser.Name;
            currentDevice.rentSurname = currentUser.Surname;
            dataGridDeviceList.Items.Refresh();
            sw.WriteLine();
            sw.Close();                
            MessageBox.Show("Rent done. Thanks!");
            tabControl.SelectedItem = mainTab;
        }
        else
        {
            MessageBox.Show("We don't have such device. Sorry :( ");
            userIDTextBox.Clear();
            deviceIDTextBox.Clear();
        }
    }

现在,问题是,我可以在程序工作期间正常处理这个文件,它会改变值,可以读取它等等,但当我关闭应用程序(通过X按钮)时,什么都不会发生。TXT文件未被触动,也未保存任何更改。

您没有向该文件写入任何内容

sw.WriteLine(); // you need to pass a string in to this function

在我看来,您一定发明了一种理论,即您对
currentDevice
所做的任何更改都会以某种方式影响写入
sw
的内容。你在这里看到的是卡尔·波普尔(Karl Popper)曾经称之为“不确定”:你的理论预测了可以观察到的行为;你观察;这种行为没有发生。第一个解释是你的理论是错误的

事实上,这是对你(没有)看到的东西的正确解释。
currentDevice
sw
之间绝对没有任何连接。没有一个这就像你按下微波炉上的按钮试图启动你的汽车。如果你不换一种方法,你将步行去上班

currentDevice.Availability = false;
currentDevice.rentId = currentUser.Id;
currentDevice.rentName = currentUser.Name;
currentDevice.rentSurname = currentUser.Surname;
dataGridDeviceList.Items.Refresh();
sw.WriteLine();
sw.Close();
您所要做的就是更改一个随机对象上的一组属性,刷新数据网格,然后向输出流写入一个换行符、一个换行符等。为什么
sw.WriteLine(),没有参数,是否执行此操作?嗯,它这样做是因为设计师们决定它会这样做。它理智地做不到别的,因为你没有给它写任何东西。这种行为被记录下来,如果你花了十秒钟,你就会知道

如果要将非空行写入文件,请使用多行中的一行。如果您只想写一行的一部分,请使用其中一行

类似这样的东西就可以了(我猜您的字段名;如果您不知道它们是什么,可能StackOverflow上的其他人知道您的代码的这一部分是什么样子,可以帮助您):

但这很难看。所以我们将把它滚动到一个方法中来隐藏它。这被称为“重构”

…并在事件处理程序中调用该方法。另请注意,对
StreamWriter
使用
语句。这将正确地处理它,从而关闭文件,等等。这很重要

private void rentSaveButton_Click(object sender, RoutedEventArgs e)
{
    using (StreamWriter sw = new StreamWriter(@"D:\deviceLib.txt", true))
    {
        var currentUser = _list.Where(u => u.Id == int.Parse(userIDTextBox.Text)).FirstOrDefault();

        var currentDevice = _list2.Where(i => i.deviceId == int.Parse(deviceIDTextBox.Text)).FirstOrDefault();
        if (currentDevice != null &&  currentUser != null)
        {
            currentDevice.Availability = false;
            currentDevice.rentId = currentUser.Id;
            currentDevice.rentName = currentUser.Name;
            currentDevice.rentSurname = currentUser.Surname;
            dataGridDeviceList.Items.Refresh();

            //  Call write method
            WriteDeviceStateToStream(sw, currentDevice);

            //  The user's going to get real tired of this messagebox real fast. 
            MessageBox.Show("Rent done. Thanks!");
            tabControl.SelectedItem = mainTab;
        }
        else
        {
            MessageBox.Show("We don't have such device. Sorry :( ");
            userIDTextBox.Clear();
            deviceIDTextBox.Clear();
        }
    }
}

那么,如果你关闭应用程序,你是否单击了保存?您是否已跟踪此代码?是否尝试设置断点?通常,前面的行是相同的,因为
newstreamwriter(@“D:\deviceLib.txt”,true)
告诉StreamWriter在目标文件中追加新行。这是一个CSV文件。您还应该为StreamWriter使用using语句。我认为重写ToString和,或者创建一个新的方法,如ToStringForFile()。对我来说,对一个流执行所有这些单独的写调用似乎很笨拙。当然,您也可以了解为什么我们将它们存储为文件中的逗号分隔值……同意,字符串化方法将更加灵活。字符串化方法可以更短:
object[]elements=new[]{x.deviceid,x.model,x.availability,x.renterID,x.renterName,x.renterName,x.OS};sw.WriteLine(string.Join(“,”元素))
public void WriteDeviceStateToStream(StreamWriter stream, WhateverTheDeviceClassIs device)
{
    //  Write fields in desired order of appearance in the file. 
    stream.Write(device.deviceID);
    //  There are many far superior ways to write a comma to the file, 
    //  and I'll hear about all of them in comments, but we're keeping 
    //  it as simple as possible for the moment.  
    stream.Write(",");
    stream.Write(device.model);
    stream.Write(",");

    //  Properties you just set
    stream.Write(device.Availability);
    stream.Write(",");
    stream.Write(device.rentID);
    stream.Write(",");
    stream.Write(device.rentName);
    stream.Write(",");
    stream.Write(device.rentSurname);
    stream.Write(",");

    stream.Write(device.OS);

    //  NOW write a newline.
    stream.WriteLine();

    //  DO NOT close the stream here. The stream belongs to the caller; make no 
    //  assumptions about what he plans to do with it next. 
}
private void rentSaveButton_Click(object sender, RoutedEventArgs e)
{
    using (StreamWriter sw = new StreamWriter(@"D:\deviceLib.txt", true))
    {
        var currentUser = _list.Where(u => u.Id == int.Parse(userIDTextBox.Text)).FirstOrDefault();

        var currentDevice = _list2.Where(i => i.deviceId == int.Parse(deviceIDTextBox.Text)).FirstOrDefault();
        if (currentDevice != null &&  currentUser != null)
        {
            currentDevice.Availability = false;
            currentDevice.rentId = currentUser.Id;
            currentDevice.rentName = currentUser.Name;
            currentDevice.rentSurname = currentUser.Surname;
            dataGridDeviceList.Items.Refresh();

            //  Call write method
            WriteDeviceStateToStream(sw, currentDevice);

            //  The user's going to get real tired of this messagebox real fast. 
            MessageBox.Show("Rent done. Thanks!");
            tabControl.SelectedItem = mainTab;
        }
        else
        {
            MessageBox.Show("We don't have such device. Sorry :( ");
            userIDTextBox.Clear();
            deviceIDTextBox.Clear();
        }
    }
}