如何使用C#将列表项及其索引保存在文本文件中

时间:2019-02-13 11:47:45

标签: c# c#-2.0

我已经在c#中创建了一个列表,现在我需要将该列表保存在文本文件中,并为列表中的每个项目都添加索引?请举一个简单的例子。

1 个答案:

答案 0 :(得分:4)

尝试以下代码:我希望您将从中获得基本的想法。

namespace ConsoleApp
{
    class Program
    {
        static void Main(string[] args)
        {
            List<string> _names = new List<string>()
            {
                "Rehan",
                "Hamza",
                "Adil",
                "Arif",
                "Hamid",
                "Hadeed"
            };

            using (StreamWriter outputFile = new StreamWriter(@"E:\test.txt")
            {
                foreach (string line in _names)
                    outputFile.WriteLine(line);
            }
        }
    }
}

或者您也应该尝试循环。

namespace ConsoleApp
{
    class Program
    {
        static void Main(string[] args)
        {
            List<string> _names = new List<string>()
            {
                "Rehan",
                "Hamza",
                "Adil",
                "Arif",
                "Hamid",
                "Hadeed"
            };

            using (StreamWriter outputFile = new StreamWriter(@"E:\test.txt")
            {
                for (int index = 0; index < _names.Count; index++)
                    outputFile.WriteLine("Index : " + index + " - " + _names[index]);
            }
        }
    }
}
  

根据您在下面的评论:   如何将列表数据保存到SQL Server表中。您可以按照   与上面的代码相同的原理:

代码:

namespace ConsoleApp
{
    class Program
    {
        static void Main(string[] args)
        {
            // Table 
            // -------------
            // | ID | Name |
            // -------------

           // Please Not that: ID Column in a database should not be identity Colomn because in this example i am going to add data to ID Column explicity...                

            // List of name that we are going to save in Database.
            List<string> _names = new List<string>()
            {
                "Rehan",
                "Hamza",
                "Adil",
                "Arif",
                "Hamid",
                "Hadeed"
            };

            SqlConnection connection = new SqlConnection("Connection string goes here...");
            connection.Open();
            for (int index = 0; index < _names.Count; index++)
            {
                SqlCommand command = new SqlCommand("INSERT INTO tbl_names (id,name) VALUES ('"+index+"', '"+_names[index]+"')",connection);
                command.ExecuteNonQuery();
            }
            connection.Close();
        }
    }
}
  

注意::使用这种语法new SqlCommand("INSERT INTO tbl_names...可能会导致SQL注入,因此避免使用存储过程。...