I have a CSV file with 48 rows of integers. I am using the openfiledialog feature of visual c# to allow a user to select this file. I then want to have the program truncate that file down to 24 rows. Is there a truncate function I can use to do this easily? If not how can I go about doing so? Below is what I have so far...
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace sts_converter
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void select_Click(object sender, EventArgs e)
{
int size = -1;
DialogResult result = openFileDialog1.ShowDialog(); // Show the dialog.
if (result == DialogResult.OK) // Test result.
{
string file = openFileDialog1.FileName;
try
{
string text = File.ReadAllText(file);
size = text.Length;
}
catch (IOException)
{
}
}
Console.WriteLine(size); // <-- Shows file size in debugging mode.
Console.WriteLine(result); // <-- For debugging use only.
}
}
}
It could be as easy as:
string file = openFileDialog1.FileName;
File.WriteAllLines(
file,
File.ReadLines(file).Take(28).ToArray()
);
Call ReadAllLines to get an array of 48 strings
Create a new array of 24 strings
Use Array.Copy to copy the strings that you want
Call WriteAllLines to write the new array to the file
(You can also use LINQ's Take method)
Related
This question already has answers here:
Reading file content to string in .Net Compact Framework
(4 answers)
Closed 3 years ago.
Here I have a csv file of data, 8 strings every line. I need to read it out from csv and display it on screen through a ListView controls.
I created a List<string[]> for data adding to ListView control. And I need to read data from csv into List. The system I used is a industrial HMI, which use WinCE OS, and vendor claims that it support .NET Compact Framework totally.
The problem I encountered is, when I use File.ReadLines(path) to read a line form csv file, error occurs when compiling, and the message show "System.IO.File" does not contain a definition for "ReadLines"
I also tried StreamReader, same problem.
namespace Neo.ApplicationFramework.Generated
{
using System.Windows.Forms;
using System;
using System.Drawing;
using Neo.ApplicationFramework.Tools;
using Neo.ApplicationFramework.Common.Graphics.Logic;
using Neo.ApplicationFramework.Controls;
using Neo.ApplicationFramework.Interfaces;
using System.Collections.Generic;
using System.Reflection;
using System.Collections;
using System.IO;
using System.Linq;
public partial class dmScr
{
public List<string> file = new List<string>();
public List<string[]> inforead = new List<string[]>();
void fileload_Click(System.Object sender, System.EventArgs e)
{
string fileName = (CB_filelist.SelectedItem != null) ?
GetStorageCard() + CB_filelist.SelectedItem.ToString() :
"";
if(fileName != null && fileName != "")
{
fileRead(fileName);
}
LV_event.Items.Clear();
inforead.ForEach(x =>
{
ListViewItem lvi = new ListViewItem(x);
LV_event.Items.Add(lvi);
});
}
private void fileRead(string fileName)
{
foreach(string[] item in File.ReadLines(fileName))
inforead.Add(s);
}
}
}
The industrial HMI vendor is Beijer, would be familiar if you're working in related field.
I am not sure CE supports File.ReadLines (not completely sure, don't quote me on this)
However StreamReader has a method called StreamReader.ReadLine
Example
using (StreamReader sr = new StreamReader(path))
{
while (sr.Peek() >= 0)
{
Console.WriteLine(sr.ReadLine());
}
}
I am trying to read a file into a string which then I will send to another application.
using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace FileApplication
{
class Program
{
static void Main(string[] args)
{
try
{
// Create an instance of StreamReader to read from a file.
// The using statement also closes the StreamReader.
using (StreamReader sr = new StreamReader("c:\text.txt"))
{
string line;
// Read and display lines from the file until
// the end of the file is reached.
while ((line = sr.ReadLine()) != null)
{
Console.WriteLine(line);
}
}
}
catch (Exception e)
{
// Let the user know what went wrong.
Console.WriteLine("The file could not be read:");
Console.WriteLine(e.Message);
}
Console.ReadKey();
}
}
}
I am getting the error:
The file could not be read:
Could not find file 'c:\users\andymarkmn\documents\visual studio 2015\Projects\FileApplication\FileApplication\bin\Debug\text.txt'.
I have tried putting the file in bin debug folders as well.
How to make sure the code works ?
EDIT: As suggested, I tried using the different ways.
using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace FileApplication
{
class Program
{
static void Main(string[] args)
{
string filepath = "c:\\text.txt";
try
{
string lines = File.ReadAllText(filepath);
Console.Write(lines);
}
catch (Exception e)
{
// Let the user know what went wrong.
Console.WriteLine("The file could not be read:");
Console.WriteLine(e.Message);
}
Console.ReadKey();
}
}
}
I still get the error:
The file could not be read:
Could not find file 'c:\text.txt'.
You have accidentally used an unwanted escape sequence in your filename string.
new StreamReader("c:\text.txt")
should be
new StreamReader(#"c:\text.txt")
Otherwise \ gets treated as an escape character, at \t is a tab character. This leaves an unexpected result, and the wrong path for the file.
# instructs the compiler to ignore any escape characters in the string.
"c:\text.txt" will not work as \ is an escape character.
use #"c:\text.txt" or "c:\\text.txt"
When StreamReader is given a non-qualified path as a parameter, it will look for the file in the application's working directory as you have done:
using (StreamReader sr = new StreamReader("c:\text.txt"))
If the file isn't located there, probably you should give StreamReader a fully qualified path:
using (StreamReader sr = new StreamReader(#"c:\text.txt"))
//or...
using (StreamReader sr = new StreamReader("c:\\text.txt"))
Try:
using (StreamReader sr = new StreamReader(#"C:\text.txt"))
If you use c:\text, C# considers that the string has a tabulador between C: and text.txt.
With this class i'm trying to make the comparison today:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.IO;
using mws;
using System.Data.SqlClient;
using System.Text.RegularExpressions;
using DannyGeneral;
namespace General_utility
{
static class File_Utility
{
static public bool File_Comparison(string Filename_1, string Filename_2)
{
FileInfo fi;
int i;
byte[] a,b;
a=File.ReadAllBytes(Filename_1);
b=File.ReadAllBytes(Filename_2);
fi = new FileInfo(a.ToString());
if (a.Length != b.Length)
{
return false;
}
else
{
for (i = 0; i < a.Length; i++)
{
if (a[i] != b[i])
return false;
}
}
return true;
}
}
}
Then i'm using it this way:
file_compare = File_Utility.File_Comparison(temp_sat_dir, last_file_satellite);
file_compare is a bool
temp_sat_dir is the current downloaded file: C:\Users\temp\satellite.jpg
The file in temp_sat_dir will be allways the same name.
And last_file_satellite is the last file downloaded and that i copied to a new directory: C:\Users\satelliteImages\SatImage000863.gif
Then i decide if to download the next files i need or not. If the first current file is not the same then continue and download the rest of the files but if it's identical don't download the rest:
if (file_compare == true)
{
break;
}
else
{
try
{
client1.DownloadFile(link, filePath);
}
catch (Exception e)
{
DannyGeneral.Logger.Write(e.ToString());
}
}
The first time file_compare was false and it downloaded the file using client1.
All my code is in loop i didn't show it here but it's in a loop and it's downloading each 15 minutes new 9 files.
But the problem is that if i run the program over again or if 15 minutes passed it will keep download the same 9 images.
I need somehow to make it download only if the first file is not the same like the last one.
The problem is that file_compare is false now again. First it downloaded the 9 files now i ran the program again and still it's false. And the images are the same i checked. The file satellite.jpg and SatImage000863.gif are the same so it should doing the break;
But it dosen't it give false.
When you copied the file to "C:\Users\satelliteImages\SatImage000863.gif", you apparently saved it instead of copying. Even if you save it as a .jpg file, it will probably not be identical to the original. Instead of doing an image save, use system.io.file.copy (or move) to copy the original file so it can be compared with the next one downloaded.
I have a few reports that are exported to Excel. The problem is whereever there are special characters, it is being replaced by some funny symbols
For example, '-'(hyphen) was replaced by –...
Any help to solve the problem??
The most straight forward way is to encode the text file as UTF-8. I ran the following code, opened the resulting hyphen.txt file in Excel 2007 and it worked as expected:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
var hyphen = "\u2010\r\n";
var encoding = Encoding.UTF8;
var bytes = encoding.GetBytes(hyphen);
using (var stream = new System.IO.FileStream(#"c:\tmp\hyphen.txt", System.IO.FileMode.Create, System.IO.FileAccess.ReadWrite))
{
stream.Write(bytes, 0, bytes.Length);
}
}
}
}
This is the code -- view at PasteBin.
I am not a programmer, but I am a researcher and I need to modify some files.
I have a number of text files with *.mol extension located in c:\abc\ directory . I need to append line containing following text "M END" to each file in this list. I tried following in C# but without any result:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
namespace ConsoleApplication3
{
class Program
{
static void Main(string[] args)
{
StreamWriter sw = new StreamWriter("c:\\abc\\*.mol", true);
sw.WriteLine("M END");
sw.Close();
}
}
}
Please, suggest the solution.
Thank You!
Would you be satisfied with this oneliner that you can put in any DOS batch (.bat) file:
FOR %%I IN (c:\abc\*.mol) DO ECHO M END>>%%I
foreach (string fileName in Directory.GetFiles("directory", "*.mol"))
{
File.AppendAllText(fileName, Environment.NewLine + "M END");
}
You'll need to loop through all the files matching that pattern and write to them individually. The StreamWriter constructor you're using only supports writing to an individual file (source).
You can get a list of files using:
string[] filePaths = Directory.GetFiles("c:\\abc\\", "*.mol");
You need to iterate over the files in the directory. DirectoryInfo / FileInfo makes it easy to do this. Also, since you want to append to the end, you need to seek the stream before writing your signature at the end.
Here's a solution that works solely at that location. You will need to add recursive support to descend into subdirectories if desired.
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
namespace appender
{
class Program
{
static void AppendToFile(FileInfo fi)
{
if (!fi.Exists) { return; }
using (Stream stm = fi.OpenWrite())
{
stm.Seek(0, SeekOrigin.End);
using (StreamWriter output = new StreamWriter(stm))
{
output.WriteLine("M END");
output.Close();
}
}
}
static void Main(string[] args)
{
DirectoryInfo di = new DirectoryInfo("C:\\abc\\");
FileInfo[] fiItems = di.GetFiles("*.mol");
foreach (FileInfo fi in fiItems)
{
AppendToFile(fi);
}
}
}
}