-1

我在试图弄清楚这一点时遇到了麻烦。当我认为我拥有它时,我被告知没有。这是它的图片。 在此处输入图像描述

我正在处理保存按钮。现在,在用户添加名字、姓氏和职位后,他们可以保存它。如果用户加载文件并且它出现在列表框中,则该人应该能够单击名称,然后单击编辑按钮,他们应该能够对其进行编辑。我有代码,但我确实得到通知,它看起来很古怪,字符串应该有名字、姓氏和职位。

当我学习 C# 时,这让我非常困惑。我知道如何使用 savefiledialog,但我不允许在这个上使用它。这是我应该做的事情:

当用户单击“保存”按钮时,将所选记录写入 txtFilePath 中指定的文件(绝对路径不是相对路径),而不截断当前内部的值。

我仍在处理我的代码,因为我被告知在一组三个字符串中写入记录会更好。但这是我现在拥有的代码。

    private void Save_Click(object sender, EventArgs e)
    {

            string path = txtFilePath.Text;


            if (File.Exists(path))
            {
                using (StreamWriter sw = File.CreateText(path))
                {

                    foreach (Employee employee in employeeList.Items)
                        sw.WriteLine(employee);
                }
            }
            else
                try
            {

                StreamWriter sw = File.AppendText(path);

                foreach (var item in employeeList.Items)
                    sw.WriteLine(item.ToString());

            }

    catch
{
    MessageBox.Show("Please enter something in");
}

现在我不能使用保存或打开文件对话框。用户应该能够打开 C、E、F 驱动器上或其所在位置的任何文件。我还被告知它应该是 obj.Also 程序应该处理和出现的异常。

我知道这可能是一个菜鸟问题,但我的思绪被卡住了,因为我仍在学习如何使用 C# 进行编码。现在我一直在寻找和阅读。但是我没有找到可以帮助我理解如何将所有这些都包含在 1 个代码中的东西。如果有人可以提供帮助,甚至可以指出一个更好的网站,我将不胜感激。

4

3 回答 3

1

您必须确定适合您需要的储蓄方式。存储此信息的一种简单方法是 CSV:

"Firstname1","Lastname 1", "Jobtitle1"
" Firstname2", "Lastname2","Jobtitle2 "

如您所见,数据不会被截断,因为分隔符"用于确定字符串边界。

这个问题所示,使用CsvHelper可能是一种选择。但鉴于这是家庭作业和其中的限制,您可能必须自己创建此方法。您可以将其放入Employee(或制作override ToString())中,以执行以下操作:

public String GetAsCSV(String firstName, String lastName, String jobTitle)
{
    return String.Format("\"{0}\",\"{1}\",\"{2}\"", firstName, lastName, jobTitle);
}

我将把如何读回数据的方法留给你作为练习。;-)

于 2012-04-27T11:09:28.433 回答
1

当您使用 WriteLine 编写员工对象时,正在调用底层的 ToString()。您首先要做的是自定义 ToString() 方法以满足您的需求,以这种方式:

public class Employee
{
    public string FirstName;
    public string LastName;
    public string JobTitle;

    // all other declarations here
    ...........

    // Override ToString()
    public override string ToString()
    { 
         return string.Format("'{0}', '{1}', '{2}'", this.FirstName, this.LastName, this.JobTitle);
    }
}

这样,您的编写代码仍然保持干净和可读。

顺便说一句,没有 ToSTring 的反向等效项,但要遵循 .Net 标准,我建议您实现 Employee 的方法,例如:

public static Employee Parse(string)
{
        // your code here, return a new Employee object
}
于 2012-04-27T11:39:03.600 回答
1

有很多很多方法可以将数据存储在文件中。此代码演示了 4 个非常易于使用的方法。但关键是您可能应该将数据拆分成单独的部分,而不是将它们存储为一个长字符串。

public class MyPublicData
{
  public int id;
  public string value;
}

[Serializable()]
class MyEncapsulatedData
{
  private DateTime created;
  private int length;
  public MyEncapsulatedData(int length)
  {
     created = DateTime.Now;
     this.length = length;
  }
  public DateTime ExpirationDate
  {
     get { return created.AddDays(length); }
  }
}

class Program
{
  static void Main(string[] args)
  {
     string testpath = System.IO.Path.Combine(
        Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "TestFile");

     // Method 1: Automatic XML serialization
     // Requires that the type being serialized and all its serializable members are public
     System.Xml.Serialization.XmlSerializer xs = 
        new System.Xml.Serialization.XmlSerializer(typeof(MyPublicData));
     MyPublicData o1 = new MyPublicData() {id = 3141, value = "a test object"};
     MyEncapsulatedData o2 = new MyEncapsulatedData(7);
     using (System.IO.StreamWriter w = new System.IO.StreamWriter(testpath + ".xml"))
     {
        xs.Serialize(w, o1);
     }

     // Method 2: Manual XML serialization
     System.Xml.XmlWriter xw = System.Xml.XmlWriter.Create(testpath + "1.xml");
     xw.WriteStartElement("MyPublicData");
     xw.WriteStartAttribute("id");
     xw.WriteValue(o1.id);
     xw.WriteEndAttribute();
     xw.WriteAttributeString("value", o1.value);
     xw.WriteEndElement();
     xw.Close();

     // Method 3: Automatic binary serialization
     // Requires that the type being serialized be marked with the "Serializable" attribute
     using (System.IO.FileStream f = new System.IO.FileStream(testpath + ".bin", System.IO.FileMode.Create))
     {
        System.Runtime.Serialization.Formatters.Binary.BinaryFormatter bf = 
           new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
        bf.Serialize(f, o2);
     }

     // Demonstrate how automatic binary deserialization works
     // and prove that it handles objects with private members
     using (System.IO.FileStream f = new System.IO.FileStream(testpath + ".bin", System.IO.FileMode.Open))
     {
        System.Runtime.Serialization.Formatters.Binary.BinaryFormatter bf =
           new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
        MyEncapsulatedData o3 = (MyEncapsulatedData)bf.Deserialize(f);
        Console.WriteLine(o3.ExpirationDate.ToString());
     }

     // Method 4: Manual binary serialization
     using (System.IO.FileStream f = new System.IO.FileStream(testpath + "1.bin", System.IO.FileMode.Create))
     {
        using (System.IO.BinaryWriter w = new System.IO.BinaryWriter(f))
        {
           w.Write(o1.id);
           w.Write(o1.value);
        }
     }

     // Demonstrate how manual binary deserialization works
     using (System.IO.FileStream f = new System.IO.FileStream(testpath + "1.bin", System.IO.FileMode.Open))
     {
        using (System.IO.BinaryReader r = new System.IO.BinaryReader(f))
        {
           MyPublicData o4 = new MyPublicData() { id = r.ReadInt32(), value = r.ReadString() };
           Console.WriteLine("{0}: {1}", o4.id, o4.value);
        }
     }
  }
}
于 2012-04-27T11:47:45.437 回答