using System.IO;

        public void CreateFile(List<DataObject> items, String tempFileLocation, String fileName)
        {

            String filePath = String.Format("{0}\\{1}", tempFileLocation, fileName);

            if (File.Exists(filePath))
            {
                File.Delete(filePath);
            }

            using (StreamWriter writer = new StreamWriter(filePath,true))
            {
                foreach (var item in items)
                {
              
                    String record = String.Format("{0},{1},{2},{3},{4},{5},{6},{7},{8}",
                        item.ID,
                        item.CompanyName,
                        item.LastName,
                        item.FirstName,
                        item.Address1,
                        item.Address2,
                        item.City,
                        item.State,
                        item.Zip);

                    writer.WriteLine(record);
                }

                writer.Close();
            }
        }

For tab delimited…

String record = String.Format("{0}\t{1}\t{2}\t{3}\t{4}\t{5}\t{6}\t{7}\t{8}",
                        item.ID,
                        item.CompanyName,
                        item.LastName,
                        item.FirstName,
                        item.Address1,
                        item.Address2,
                        item.City,
                        item.State,
                        item.Zip);

For tab delimited and exact position…

        private string Truncate(string value, int maxLength)
        {
            if (string.IsNullOrEmpty(value)) return "".PadRight(maxLength);
            return value.Length <= maxLength ? value.PadRight(maxLength) : value.Substring(0, maxLength);
        }

  String record = String.Format("{0}\t{1}\t{2}\t{3}\t{4}\t{5}\t{6}\t{7}\t{8}",
                        Truncate(item.ID,12),
                        Truncate(item.CompanyName, 90),
                        Truncate(item.LastName, 50),
                        Truncate(item.FirstName, 50),
                        Truncate(item.Address1, 35),
                        Truncate(item.Address2, 35),
                        Truncate(item.City, 20),
                        Truncate(item.State, 2),
                        Truncate(item.Zip, 10));
Last modified: July 1, 2019

Author

Comments

Write a Reply or Comment