"System.IO.File" does not contain a definition for "ReadLines" [duplicate] - c#

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());
}
}

Related

Programmatically change/add thumbnail of pptx powerpoint. With Openxml sdk?

I use openxml sdk 2.5 in combination with the power tools by Eric White. I've managed to create dynamic pptx presentations using template files. (In C#)
Unfortunately the thumbnail gets lost during the process. Is there any way to (re)create the thumbnail of a pptx-file using openxml or power tools? I successfully wrote some code that changes an existing thumbnail with an image. But when there is is no thumbnail it gives me a System.NullReferenceException. Here is the code:
using OpenXmlPowerTools;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using DocumentFormat.OpenXml.Packaging;
namespace ConsoleApplication1
{
class AddThumbnail_
{
public static void ReplaceThumbnail(ThumbnailPart thumbnailPart, string newThumbnail)
{
using (
FileStream imgStream = new FileStream(newThumbnail, FileMode.Open, FileAccess.Read))
{
thumbnailPart.FeedData(imgStream);
}
}
static void Main(string[] args)
{
var templatePresentation = "Modified.pptx";
var outputPresentation = "Modified.pptx";
var baPresentation = File.ReadAllBytes(templatePresentation);
var pmlMainPresentation = new PmlDocument("Main.pptx", baPresentation);
OpenXmlMemoryStreamDocument streamDoc = new OpenXmlMemoryStreamDocument(pmlMainPresentation);
PresentationDocument document = streamDoc.GetPresentationDocument();
var thumbNailPart = document.ThumbnailPart;
ReplaceThumbnail(thumbNailPart, #"C:\Path\to\image\image.jpg");
document.SaveAs(outputPresentation);
}
}
}
EDIT:
I realize this question has been asked before (How to generate thumbnail image for a PPTX file in C#?) and the answer is "enable preview screenshot when saving the presentation" but this would mean I'd have to open every pptx and manually set this flag. I would appreciate a C# solution.
Thank you in advance!
If the thumbnail has never existed then the ThumbnailPart won't necessarily exist in the document and so the thumbNailPart variable in your code will be null. In that scenario, as well as setting the image for the ThumbnailPart you need to add the part itself.
Normally when using the OpenXml SDK you would call the AddPart method passing in a new ThumbnailPart but for some reason the ThumbnailPart constructor is protected internal and thus not accessible to you. Instead, there is an AddThumbnailPart method on the PresentationDocument which will create a new ThumbnailPart. The AddThumbnailPart method takes either a string for the content type or a ThumbnailPartType enum member.
Adding the following to your code should fix your issue:
if (document.ThumbnailPart == null)
document.AddThumbnailPart(ThumbnailPartType.Jpeg);
var thumbNailPart = document.ThumbnailPart;

Read a file into a string in C#

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.

How can i compare if last downloaded satellite image and the current downloaded satellite image are identical or not?

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.

Truncate CSV file in C#

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)

How to append text to multiple files

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);
}
}
}
}

Categories