How to get encoding when I read a .csv File? - c#

As title, the following code...
System.IO.FileInfo _fInfo;
OpenFileDialog openDlg = new OpenFileDialog();
openDlg.Filter = "Csv Files (.csv)|*.csv";
openDlg.FilterIndex = 1;
openDlg.Multiselect = false;
bool? userClickedOK = openDlg.ShowDialog();
if (userClickedOK == true)
{
_fInfo = openDlg.File;
}
Stream fileStream = _fInfo.OpenRead();
using (System.IO.StreamReader reader = new StreamReader(fileStream))
{
int lineNo = 1;
while (!reader.EndOfStream)
{
reader.ReadLine();
}
}
Is any way to find "_fInfo" current encoding?
PS: I used silverlight console(silverlight 2.0).

Try StreamReader.CurrentEncoding after first read. The reader will try to detect encoding.

Related

C# - Trying to grab and save a pdf into my database

In my C# application, I am trying to make it able to pull a pdf and save it, so that end users can press a button and pull up that pdf while they are in the application. But when I copy the content to the filestream it makes the pdf but it is just blank with nothing from the original pdf. What am I doing wrong?
The pdf's could also have pictures on them, and I don't think the way I'm doing it would allow those to be brought over.
Microsoft.Win32.OpenFileDialog openFileDialog = new Microsoft.Win32.OpenFileDialog();
bool? response = openFileDialog.ShowDialog();
var fileContent = string.Empty;
var filestream = openFileDialog.OpenFile();
using (StreamReader reader = new StreamReader(filestream))
{
fileContent = reader.ReadToEnd();
}
// make folder path
string FolderPath = "ProjectPDFs\\";
string RootPath = "X:\\Vents-US Inventory";
DirectoryInfo FolderDir = new DirectoryInfo(Path.Combine(RootPath, FolderPath));
Directory.CreateDirectory(FolderDir.ToString());
string filePath = "";
string FileName = openFileDialog.SafeFileName;
if (fileContent.Length > 0)
{
filePath = Path.Combine(FolderDir.ToString(), FileName);
using (Stream fileStream = new FileStream(filePath, FileMode.Create, FileAccess.Write))
{
byte[] bytestream = Encoding.UTF8.GetBytes(fileContent);
Stream stream = new MemoryStream(bytestream);
stream.CopyTo(fileStream);
}
}

How do I consume a file resource as a string, in Visual Studio?

When I add a txt file as a resource to a project, how can I then consume the contents of that resource as a string?
The closest I've been able to get is by using the Resource Manager, to pull an unmanaged stream. However, this throws a null error:
using (StreamReader sr = new StreamReader(
Properties.Resources.ResourceManager.GetStream(
"TestFile.txt", CultureInfo.CurrentCulture)))
{
Console.WriteLine(sr.ReadToEnd());
}
You could do this too:
var myAss = Assembly.GetExecutingAssembly();
var mytxtFileResource = "Namespace.Project.MyTxtFile.txt";
using (Stream stream = assembly.GetManifestResourceStream(mytxtFileResource))
using (StreamReader reader = new StreamReader(stream))
{
string result = reader.ReadToEnd();
}
You dont need to do it like that for text files
Just write it like this
https://msdn.microsoft.com/en-us/library/aa287548(v=vs.71).aspx
System.IO.StreamWriter file = new System.IO.StreamWriter("c:\\test.txt");
file.WriteLine(lines);
file.Close();
and read it like this:
https://msdn.microsoft.com/en-us/library/aa287535(v=vs.71).aspx
int counter = 0;
string line;
// Read the file and display it line by line.
System.IO.StreamReader file =
new System.IO.StreamReader("c:\\test.txt");
while((line = file.ReadLine()) != null)
{
Console.WriteLine (line);
counter++;
}
file.Close();

Open and Read a text file Located in a SharePoint Document Library using CSOM

I'm able to get the relative path to a file in SharePoint. I now need to open the file and read its contents. This is where I'm stuck. I don't know how to open a file for reading unless it is local to my hard drive, which it is not. Here is my code:
If item.FieldValues("File_x0020_Type") = "html" Then
Dim the_file As SP.File = oWebsite.GetFileByServerRelativeUrl(item.FieldValues("FileRef"))
Dim reader As StreamReader = New StreamReader(the_file)
Dim sr As StreamReader = StreamReader(the_file)
textbox1.text = sr.ReadToEnd()
reader.Close()
End If
Sorry misread that.
ClientContext clientContext = new ClientContext("http://SpSiteUrl");
clientContext.ExecuteQuery();
FileInformation fileInfo = Microsoft.SharePoint.Client.File.OpenBinaryDirect(clientContext, "thisFile");
System.IO.Stream stream = fileInfo.Stream;
using (StreamReader r = new StreamReader(stream))
string line;
while((line = file.ReadLine()) != null)
{
System.Console.WriteLine (line);
}
}
Once it is set to the Stream, you should be able to loop through it normally.
I also saw this second method.
using (var clientContext = new ClientContext(url)) {
Microsoft.SharePoint.Client.File.OpenBinaryDirect(clientContext, "thisFile");
using (var fileStream = System.IO.File.Create(getItem))
{
fileInfo.Stream.CopyTo(fileStream);
}
}
Then you would just loop through the fileStream normally as well.
Here is a second way to loop as well -
using (StreamReader sr = new StreamReader(stream))
{
while (sr.Peek() >= 0)
{
Console.WriteLine(sr.ReadLine());
}
}
And actually, now that I am reading your question one more time - you might be able to do just this.
Dim reader As StreamReader = New StreamReader(stream)
textbox1.text = reader.ReadToEnd()
reader.Close()

WIndows Phone 7 reading file to String

I'm trying to read a file entirely to a String variable.
I did this:
String text;
using (var store = IsolatedStorageFile.GetUserStoreForApplication())
using (var readStream = new IsolatedStorageFileStream("k.dat", FileMode.Open, store))
using (var reader = new StreamReader(readStream))
{
text= reader.ReadToEnd();
}
textBlock1.Text = text;`
It gave me a "Operation not permitted on IsolatedStorageFileStream" message from an IsolatedStorageException.
What am I doing wrong?
I tried by adding a .txt and .xml file in the file name, but it didn't work.
Where am I to put the file anyway? I tried
~\Visual Studio 2010\Projects\Parsing\Parsing\k.dat
I'm parsing it later using:
XmlReader reader = XmlReader.Create(new StringReader(xmldata));
flagLink = false;
while (reader.Read())
{
//and so on
Try with..
string text;
string filename="k.txt";
using (IsolatedStorageFile isolatedStorage = IsolatedStorageFile.GetUserStoreForApplication())
{
if (isolatedStorage.FileExists(fileName))
{
StreamReader reader = new StreamReader(new IsolatedStorageFileStream(fileName, FileMode.Open, isolatedStorage));
text = reader.ReadToEnd();
reader.Close();
}
if(!String.IsNullOrEmpty(text))
{
MessageBox.Show(text);
}
}
EDIT:
In case of xml,
try
{
using (IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication())
{
IsolatedStorageFileStream isoFileStream = myIsolatedStorage.OpenFile("test.xml", FileMode.Open); //you can use your filename just like above code
using (StreamReader reader = new StreamReader(isoFileStream))
{
this.textbox1.Text = reader.ReadToEnd();
}
}
}
catch
{ }
This is the entire method and this worked fully:
String sFile = "k.dat";
IsolatedStorageFile myFile = IsolatedStorageFile.GetUserStoreForApplication();
//myFile.DeleteFile(sFile);
if (!myFile.FileExists(sFile))
{
IsolatedStorageFileStream dataFile = myFile.CreateFile(sFile);
dataFile.Close();
}
var resource = Application.GetResourceStream(new Uri(#"k.dat", UriKind.Relative));
StreamReader streamReader = new StreamReader(resource.Stream);
string rawData = streamReader.ReadToEnd();
return rawData;

Searching for string using OpenFileDialog and Multiselect

I am doing an exercise where I need to find a string in a group of files.
I manage to find the string selecting each file individually.
How can I do the same selecting all files at once.
openFileDialog.Multiselect = true;
DialogResult result = openFileDialog.ShowDialog();
string filename = openFileDialog.SafeFileName;
FileStream fs = new FileStream(filename, FileMode.Open, FileAccess.Read);
BufferedStream bs = new BufferedStream(fs);
StreamReader sr = new StreamReader(fs);
String s;
if (result == DialogResult.OK)
{
while ((s = sr.ReadLine()) != null)
{
if(s.Contains("Specified string"))
{
MessageBox.Show(filename + " Contains the Specified string");
break;
}
}
}
fs.Close();
sr.Close();
OpenFileDialog has properties (FileNames, SafeFileNames) that return all selected files.
First of all, you should use SafeFileNames Property:
if (result == DialogResult.OK)
{
foreach(string filename = openFileDialog.SafeFileName)
{
FileStream fs = new FileStream(filename, FileMode.Open, FileAccess.Read);
BufferedStream bs = new BufferedStream(fs);
StreamReader sr = new StreamReader(fs);
String s;
while ((s = sr.ReadLine()) != null)
{
if(s.Contains("Specified string"))
{
MessageBox.Show(filename + " Contains the Specified string");
break;
}
}
fs.Close();
sr.Close();
}
}
For second, you can use Parallel Class for simultaneous processing of the files.

Categories

Resources