Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/307.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# 从字符串数组创建CSV文件_C#_Arrays_Csv_Export To Csv - Fatal编程技术网

C# 从字符串数组创建CSV文件

C# 从字符串数组创建CSV文件,c#,arrays,csv,export-to-csv,C#,Arrays,Csv,Export To Csv,我正在尝试将数据从对象列表导出到csv文件。我成功地创建了文件并创建了第一行,但是我需要为每个循环创建某种类型的循环,以循环通过每个对象 这是我的代码: string pathDesktop = Environment.GetFolderPath(Environment.SpecialFolder.Desktop); string filePath = pathDesktop + "\\mycsvfile.csv"; if (!File.Exists(filePath)) { File

我正在尝试将数据从对象列表导出到csv文件。我成功地创建了文件并创建了第一行,但是我需要为每个循环创建某种类型的循环,以循环通过每个对象

这是我的代码:

string pathDesktop = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
string filePath = pathDesktop + "\\mycsvfile.csv";

if (!File.Exists(filePath))
{
    File.Create(filePath).Close();
}

string delimter = ",";
string[][] output = new string[][] { 
  new string[] {"TEST1","TEST2"} 
};

int length = output.GetLength(0);
StringBuilder sb = new StringBuilder();

for (int index = 0; index < length; index++)
{
    sb.AppendLine(string.Join(delimter, output[index]));
    File.AppendAllText(filePath, sb.ToString());
}
string pathDesktop=Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
字符串filePath=pathDesktop+“\\mycsvfile.csv”;
如果(!File.Exists(filePath))
{
File.Create(filePath.Close();
}
字符串delimter=“,”;
字符串[][]输出=新字符串[][]{
新字符串[]{“TEST1”,“TEST2”}
};
int length=output.GetLength(0);
StringBuilder sb=新的StringBuilder();
for(int index=0;index
有没有办法创建此文件并使用循环遍历所有我的对象并在文件中显示它们。

以下是解决方案:

string pathDesktop = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
string filePath = pathDesktop + "\\mycsvfile.csv";

if (!File.Exists(filePath))
{
    File.Create(filePath).Close();
}
string delimter = ",";
List<string[]> output = new List<string[]>();

//flexible part ... add as many object as you want based on your app logic
output.Add(new string[] {"TEST1","TEST2"});
output.Add(new string[] {"TEST3","TEST4"});

int length = output.Count;

using (System.IO.TextWriter writer = File.CreateText(filePath))
{
    for (int index = 0; index < length; index++)
    {
        writer.WriteLine(string.Join(delimter, output[index]));
    }
}
string pathDesktop=Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
字符串filePath=pathDesktop+“\\mycsvfile.csv”;
如果(!File.Exists(filePath))
{
File.Create(filePath.Close();
}
字符串delimter=“,”;
列表输出=新列表();
//柔性零件。。。根据应用程序逻辑添加任意数量的对象
Add(新字符串[]{“TEST1”、“TEST2”});
Add(新字符串[]{“TEST3”,“TEST4”});
int length=output.Count;
使用(System.IO.TextWriter writer=File.CreateText(filePath))
{
for(int index=0;index
假设obj是一个字符串列表,我通常使用这个

System.IO.File.WriteAllLines(stringFilePath, obj.ToArray());

如果您想要一个通用扩展名,它将遍历列表中的每个项目,将其添加到新行,并使用getter遍历每个公共属性,并在该行上为每个属性创建一个以逗号分隔的字段列表,您可以根据或使用我的扩展名,在列表上调用扩展名,如下所示:

MyList.ToDelimitedText(",", true);
完整代码如下

using System;
using System.Collections.Generic;
using System.Reflection;
using System.Text;

namespace Gists.Extensions.ListOfTExtentions
{
    public static class ListOfTExtentions
    {
        /// <summary>
        /// Converst this instance to delimited text.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="instance">The instance.</param>
        /// <param name="delimiter">The delimiter.</param>
        /// <param name="trimTrailingNewLineIfExists">
        /// If set to <c>true</c> then trim trailing new line if it exists.
        /// </param>
        /// <returns></returns>
        public static string ToDelimitedText<T>(this List<T> instance, 
            string delimiter, 
            bool trimTrailingNewLineIfExists = false)
            where T : class, new()
        {
            int itemCount = instance.Count;
            if (itemCount == 0) return string.Empty;

            var properties = GetPropertiesOfType<T>();
            int propertyCount = properties.Length;
            var outputBuilder = new StringBuilder();

            for (int itemIndex = 0; itemIndex < itemCount; itemIndex++)
            {
                T listItem = instance[itemIndex];
                AppendListItemToOutputBuilder(outputBuilder, listItem, properties, propertyCount, delimiter);

                AddNewLineIfRequired(trimTrailingNewLineIfExists, itemIndex, itemCount, outputBuilder);
            }

            var output = TrimTrailingNewLineIfExistsAndRequired(outputBuilder.ToString(), trimTrailingNewLineIfExists);
            return output;
        }

        private static void AddDelimiterIfRequired(StringBuilder outputBuilder, int propertyCount, string delimiter,
            int propertyIndex)
        {
            bool isLastProperty = (propertyIndex + 1 == propertyCount);
            if (!isLastProperty)
            {
                outputBuilder.Append(delimiter);
            }
        }

        private static void AddNewLineIfRequired(bool trimTrailingNewLineIfExists, int itemIndex, int itemCount,
            StringBuilder outputBuilder)
        {
            bool isLastItem = (itemIndex + 1 == itemCount);
            if (!isLastItem || !trimTrailingNewLineIfExists)
            {
                outputBuilder.Append(Environment.NewLine);
            }
        }

        private static void AppendListItemToOutputBuilder<T>(StringBuilder outputBuilder, 
            T listItem, 
            PropertyInfo[] properties,
            int propertyCount,
            string delimiter)
            where T : class, new()
        {

            for (int propertyIndex = 0; propertyIndex < properties.Length; propertyIndex += 1)
            {
                var property = properties[propertyIndex];
                var propertyValue = property.GetValue(listItem);
                outputBuilder.Append(propertyValue);

                AddDelimiterIfRequired(outputBuilder, propertyCount, delimiter, propertyIndex);
            }
        }

        private static PropertyInfo[] GetPropertiesOfType<T>() where T : class, new()
        {
            Type itemType = typeof (T);
            var properties = itemType.GetProperties(BindingFlags.Instance | BindingFlags.GetProperty | BindingFlags.Public);
            return properties;
        }

        private static string TrimTrailingNewLineIfExistsAndRequired(string output, bool trimTrailingNewLineIfExists)
        {
            if (!trimTrailingNewLineIfExists || !output.EndsWith(Environment.NewLine)) return output;

            int outputLength = output.Length;
            int newLineLength = Environment.NewLine.Length;
            int startIndex = outputLength - newLineLength;
            output = output.Substring(startIndex, newLineLength);
            return output;
        }
    }
}
使用系统;
使用System.Collections.Generic;
运用系统反思;
使用系统文本;
命名空间Gists.Extensions.ListofExtensions
{
公共静态类ListofExtensions
{
/// 
///将此实例转换为带分隔符的文本。
/// 
/// 
///实例。
///分隔符。
/// 
///如果设置为true,则修剪尾随的新行(如果存在)。
/// 
/// 
公共静态字符串ToDelimitedText(此列表实例,
字符串分隔符,
bool trimTrailingNewLineIfExists=false)
其中T:class,new()
{
int itemCount=instance.Count;
if(itemCount==0)返回string.Empty;
var properties=getPropertiesOffType();
int propertyCount=properties.Length;
var outputBuilder=新的StringBuilder();
对于(int-itemIndex=0;itemIndex
调用代码的示例可以在以下测试中找到:

using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Gists.Extensions.ListOfTExtentions;

namespace Gists_Tests.ExtensionTests.ListOfTExtentionTests
{
    [TestClass]
    public class ListOfT_ToDelimitedTextTests
    {
        #region Mock Data

        private class SimpleObject
        {
            public int Id { get; set; }
        }

        private class ComplextObject : SimpleObject
        {
            public string Name { get; set; }
            public bool Active { get; set; }
        }

        #endregion

        #region Tests

        [TestMethod]
        public void ToDelimitedText_ReturnsCorrectNumberOfRows()
        {
            // ARRANGE
            var itemList = new List<ComplextObject>
            {
                new ComplextObject {Id = 1, Name = "Sid", Active = true},
                new ComplextObject {Id = 2, Name = "James", Active = false},
                new ComplextObject {Id = 3, Name = "Ted", Active = true},
            };
            const string delimiter = ",";
            const int expectedRowCount = 3;
            const bool trimTrailingNewLineIfExists = true;

            // ACT
            string result = itemList.ToDelimitedText(delimiter, trimTrailingNewLineIfExists);
            var lines = result.Split(new[] { Environment.NewLine }, StringSplitOptions.None);
            var actualRowCount = lines.Length;

            // ASSERT
            Assert.AreEqual(expectedRowCount, actualRowCount);
        }

        [TestMethod]
        public void ToDelimitedText_ReturnsCorrectNumberOfProperties()
        {
            // ARRANGE
            var itemList = new List<ComplextObject>
            {
                new ComplextObject {Id = 1, Name = "Sid", Active = true}
            };
            const string delimiter = ",";
            const int expectedPropertyCount = 3;

            // ACT
            string result = itemList.ToDelimitedText(delimiter);
            var lines = result.Split(Environment.NewLine.ToCharArray());
            var properties = lines.First().Split(delimiter.ToCharArray());
            var actualPropertyCount = properties.Length;

            // ASSERT
            Assert.AreEqual(expectedPropertyCount, actualPropertyCount);
        }

        [TestMethod]
        public void ToDelimitedText_RemovesTrailingNewLine_WhenSet()
        {
            // ARRANGE
            var itemList = new List<ComplextObject>
            {
                new ComplextObject {Id = 1, Name = "Sid", Active = true},
                new ComplextObject {Id = 2, Name = "James", Active = false},
                new ComplextObject {Id = 3, Name = "Ted", Active = true},
            };
            const string delimiter = ",";
            const bool trimTrailingNewLineIfExists = true;

            // ACT
            string result = itemList.ToDelimitedText(delimiter, trimTrailingNewLineIfExists);
            bool endsWithNewLine = result.EndsWith(Environment.NewLine);

            // ASSERT
            Assert.IsFalse(endsWithNewLine);
        }

        [TestMethod]
        public void ToDelimitedText_IncludesTrailingNewLine_WhenNotSet()
        {
            // ARRANGE
            var itemList = new List<ComplextObject>
            {
                new ComplextObject {Id = 1, Name = "Sid", Active = true},
                new ComplextObject {Id = 2, Name = "James", Active = false},
                new ComplextObject {Id = 3, Name = "Ted", Active = true},
            };
            const string delimiter = ",";
            const bool trimTrailingNewLineIfExists = false;

            // ACT
            string result = itemList.ToDelimitedText(delimiter, trimTrailingNewLineIfExists);
            bool endsWithNewLine = result.EndsWith(Environment.NewLine);

            // ASSERT
            Assert.IsTrue(endsWithNewLine);
        }

        #endregion
    }
}
使用系统;
使用System.Collections.Generic;
使用System.Linq;
使用Microsoft.VisualStudio.TestTools.UnitTesting;
使用Gists.Extensions.ListofExtensions;
命名空间Gists_Tests.ExtensionTests.ListofExtensionTests
{
[测试类]
公共类ListSoft_ToDelimitedTextTests
{
#区域
public string CSVout(string[] strArray)
{
    string sOut = "";

    foreach (void s_loopVariable in strArray) {
        s = s_loopVariable;
        if (s.Contains(","))
            s = Strings.Chr(34) + s + Strings.Chr(34);
        sOut += s + ",";
    }

    if (Strings.Right(sOut, 1) == ",")
        sOut = Strings.Left(@out, @out.Length - 1);

    return sOut;
}
  Function CSVout(strArray() As String) As String
    Dim out As String = ""

    For Each s In strArray
        If s.Contains(",") Then s = Chr(34) + s + Chr(34)
        out &= s + ","
    Next

    If Strings.Right(out, 1) = "," Then out = Strings.Left(out, out.Length - 1)

    Return out
End Function