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.
Related
I want to read Excel file from JSON data which I am sending from ARC, Can anyone help me to sorted out?
public bool ControlAttachment(AttachmentFile file)
{
try
{
if (file != null && file.File != null)
{
string xlsfile = file.File;
string [] xls = {"application/excel","application/vnd.msexcel","xls","xlsx","application/vnd.ms-excel",};
if (xls.ToList().Contains(file.FileType.Trim()))
{
file.FileType = ".xls";
byte[] contents = Convert.FromBase64String(xlsfile);
string LogFilePaths = ConfigurationManager.AppSettings["ExcelMapperPath"];
string fileName = file.FileName.Split('.')[0] + file.FileType;
string LogFile = HttpContext.Current.Server.MapPath(LogFilePaths + file.FileName.Split('.')[0] + file.FileType);
System.IO.File.WriteAllBytes(LogFile, contents);
if (!File.Exists(LogFile))
{
File.Create(LogFile).Dispose();
}
MemoryStream ms = new MemoryStream();
using (var fs = new FileStream(LogFile, FileMode.Open, FileAccess.Write))
{
ms.CopyTo(fs);
ms.Dispose();
}
}
}
return true;
}
catch
{
return false;
}
}
public bool ReadFile()
{
string fname = "text.txt";
FileStream fs = null;
fs = new FileStream(fname, FileMode.OpenOrCreate,FileAccess.Read);
StreamReader sr = new StreamReader(fs);
string res = sr.ReadToEnd();
if (res == "1")
return true;
else
return false;
}
public void WriteToFile()
{
string fname = "text.txt";
FileStream fs = null;
fs = new FileStream(fname, FileMode.Open,FileAccess.Write);
StreamWriter sw = new StreamWriter(fs);
sw.Write("1");
}
So it should work like if ReadFile returns false than i do WriteFile.
But when it reaches writefile, it throws IO expection:
The process cannot access the file ... because it is being used by another process
You aren't closing the file when you read it.
Put your FileStream and StreamReader objects in using statements:
using (var fs = new FileStream(fname, FileMode.OpenOrCreate,FileAccess.Read)) {
using (var sr = new StreamReader(fs)) {
//read file here
}
}
Make sure you do the same when you write to the file.
You need to dispose the StreamReader object in the ReadFile method. The StreamReader inherits from IDisposable and therfor you need to dispose the object.
Check this link for more info:StreamReader Class
I have my program save the contents of 4 different text boxes into 4 separate text files using IsolatedStorageFile. This works fine, until I have to load them later. When I'm loading, all 4 text files are loaded into the first text box, and the remaining 3 are left blank.
Here's the code I'm using to save the files:
private void Button_Click_2(object sender, RoutedEventArgs e)
{
defaultPicker.ItemsSource = new List<string>() { { box1.Text }, { box2.Text }, { box3.Text }, { box4.Text } };
//Deletes any previous saved files
IsolatedStorageFile storage = IsolatedStorageFile.GetUserStoreForApplication();
storage.DeleteFile("ip-1.txt");
storage.DeleteFile("ip-2.txt");
storage.DeleteFile("ip-3.txt");
storage.DeleteFile("ip-4.txt");
// This saves users IP's into text files for later loading
IsolatedStorageFile fileStorage = IsolatedStorageFile.GetUserStoreForApplication();
StreamWriter Writer = new StreamWriter(new IsolatedStorageFileStream("ip-1.txt", FileMode.OpenOrCreate, fileStorage));
Writer.WriteLine(box1.Text);
new StreamWriter(new IsolatedStorageFileStream("ip-2.txt", FileMode.OpenOrCreate, fileStorage));
Writer.WriteLine(box2.Text);
new StreamWriter(new IsolatedStorageFileStream("ip-3.txt", FileMode.OpenOrCreate, fileStorage));
Writer.WriteLine(box3.Text);
new StreamWriter(new IsolatedStorageFileStream("ip-4.txt", FileMode.OpenOrCreate, fileStorage));
Writer.WriteLine(box4.Text);
Writer.Close();
}
and to load the files later:
private void Button_Click_4(object sender, RoutedEventArgs e)
{
// Loads IP's from text file or displays error message
//First clear the boxes...
box1.Text = "";
box2.Text = "";
box3.Text = "";
box4.Text = "";
//Load from text files...
IsolatedStorageFile fileStorage = IsolatedStorageFile.GetUserStoreForApplication();
StreamReader Reader = null;
try
{
Reader = new StreamReader(new IsolatedStorageFileStream("ip-1.txt", FileMode.Open, fileStorage));
string textFile = Reader.ReadToEnd();
box1.Text = textFile;
}
catch
{
}
IsolatedStorageFile.GetUserStoreForApplication();
try
{
Reader = new StreamReader(new IsolatedStorageFileStream("ip-2.txt", FileMode.Open, fileStorage));
string textFile2 = Reader.ReadToEnd();
box2.Text = textFile2;
}
catch
{
}
IsolatedStorageFile.GetUserStoreForApplication();
try
{
Reader = new StreamReader(new IsolatedStorageFileStream("ip-3.txt", FileMode.Open, fileStorage));
string textFile3 = Reader.ReadToEnd();
box3.Text = textFile3;
}
catch
{
}
IsolatedStorageFile.GetUserStoreForApplication();
try
{
Reader = new StreamReader(new IsolatedStorageFileStream("ip-4.txt", FileMode.Open, fileStorage));
string textFile4 = Reader.ReadToEnd();
box4.Text = textFile4;
Reader.Close();
}
catch
{
}
// To sync with ListPicker
defaultPicker.ItemsSource = new List<string>() { { box1.Text }, { box2.Text }, { box3.Text }, { box4.Text } };
}
Any help into the right direction would be appreciated.
First, I suggest you stop eating all exceptions. At least in debug mode, have the empty catch blocks in a pragma.
I would drop the single declaration of Reader and create a new one per file:
try
{
using (StreamReader reader = new StreamReader(new IsolatedStorageFileStream("ip-1.txt", FileMode.Open, fileStorage)))
{
string textFile = reader.ReadToEnd();
box1.Text = textFile;
}
}
You aren't writing to the four files correctly. You need to reassign your Writer each time.
StreamWriter Writer = new StreamWriter(new IsolatedStorageFileStream("ip-1.txt", FileMode.OpenOrCreate, fileStorage));
Writer.WriteLine(box1.Text);
Writer = new StreamWriter(new IsolatedStorageFileStream("ip-2.txt", FileMode.OpenOrCreate, fileStorage));
Writer.WriteLine(box2.Text);
Writer = new StreamWriter(new IsolatedStorageFileStream("ip-3.txt", FileMode.OpenOrCreate, fileStorage));
Writer.WriteLine(box3.Text);
Writer = new StreamWriter(new IsolatedStorageFileStream("ip-4.txt", FileMode.OpenOrCreate, fileStorage));
Writer.WriteLine(box4.Text);
Writer.Close();
In the future you should have something in your catch blocks to display any caught exceptions. In this case it would have told you that the three other files weren't able to be loaded because they didn't exist.
I'm writing simple method that should read data from the text file.I can't understand why this method read only 2nd, 4th, 6 lines? Method is below. What is wrong in my code?
public static List<Employee> ReadFromFile(string path = "1.txt")
{
List<Employee> employees = new List<Employee>();
Stream stream = null;
StreamReader sr = null;
try
{
stream = new FileStream(path, FileMode.Open, FileAccess.Read);
stream.Seek(0, SeekOrigin.Begin);
sr = new StreamReader(stream);
string line;
while ((line = sr.ReadLine()) != null)
{
Employee employee = new DynamicEmployee();
string str = sr.ReadLine();
employee.FirstName = str.Substring(1, 20).Trim();
employee.LasttName = str.Substring(20, 20).Trim();
employee.Paynment = Convert.ToDouble(str.Substring(40, 20).Trim());
Console.WriteLine("{0} {1} {2}", employee.FirstName, employee.LasttName, employee.Paynment);
employees.Add(employee);
//Console.WriteLine(str);
}
}
catch//(System.FormatException)
{
Console.WriteLine("File format is incorect");
}
finally
{
sr.Close();
stream.Close();
}
return employees;
}
You are calling line = sr.ReadLine() twice.
Remove this line, string str = sr.ReadLine(); and use variable line
It should look like this:
public static List<Employee> ReadFromFile(string path = "1.txt")
{
List<Employee> employees = new List<Employee>();
Stream stream = null;
StreamReader sr = null;
try
{
stream = new FileStream(path, FileMode.Open, FileAccess.Read);
stream.Seek(0, SeekOrigin.Begin);
sr = new StreamReader(stream);
string line;
while ((line = sr.ReadLine()) != null)
{
Employee employee = new DynamicEmployee();
// string str = sr.ReadLine(); // WRONG, reading 2x
employee.FirstName = line.Substring(1, 20).Trim();
employee.LasttName = line.Substring(20, 20).Trim();
employee.Paynment = Convert.ToDouble(line.Substring(40, 20).Trim());
Console.WriteLine("{0} {1} {2}", employee.FirstName, employee.LasttName, employee.Paynment);
employees.Add(employee);
//Console.WriteLine(str);
}
}
catch//(System.FormatException)
{
Console.WriteLine("File format is incorect");
}
finally
{
sr.Close();
stream.Close();
}
return employees;
}
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.