Use affected file/directory to streamread to console - c#

I'm trying to actively scan recent file inputs from a directory and StreamReading the file to console. I'm having problems finding a solution to using the most recent file input and printing the whole file text lines to console. I'm using FileSystemWatcher for recent inputs.
Here's my code (I'm a beginner):
private static void filesys_created(object sender, FileSystemEventArgs e)
{
Console.WriteLine(DateTime.Now + " : New file input: {0}", e.Name + Enviroment.Newline);
try
{
using (StreamReader sr = new StreamReader(directorypath))
{
string path = directorypath
String line = sr.ReadLine(e.Name);
string filename = e.Name;
Console.WriteLine(line);
}
}
catch (exception)
{
Console.WriteLine("File could not be read to console");
}
}
Only error showing is "No overload for method "ReadLine" takes 1 argument.
& File is not streamreading text to console

You must open the file from FullPath in FileSystemEventArgs
Then, you can write to console the content of the file by ReadToEnd
using (StreamReader sr = new StreamReader(e.FullPath))
{
Console.WriteLine(sr.ReadToEnd());
}

Related

Application still says file is open and display error

I have a txt file that is loaded into a listbox when the form loads. Im trying to get this button to add to the text file. It says the file is still open. Is there a way I can make this add the path of the file selected to the listbox even if open. I'm not sure how to close this. I've been told it automatically does it.
private void shortcutManagerForm_Load(object sender, EventArgs e)
{
if (File.Exists("Shortcut_Items.txt"))
{
shortcutListBox.DataSource = File.ReadAllLines("Shortcut_Items.txt");
}
}
OpenFileDialog openFileDialog1 = new OpenFileDialog();
if (openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
string tempPath = "";
tempPath = openFileDialog1.FileName;
StreamWriter file2 = new StreamWriter("Shortcut_Items.txt", true);
string path = "Shortcut_Items.txt";
string appendText = Environment.NewLine + tempPath + Environment.NewLine;
File.AppendAllText(path, appendText);
MessageBox.Show("Shortcut added");
}
StreamWriter file2 = new StreamWriter("Shortcut_Items.txt", true);
// ...
File.AppendAllText(path, appendText);
Sure, the file is open. You create a StreamWriter that opens that file for writing. Then - completely independently of that StreamWriter - you open the file for writing again using File.AppendAllText.
Get rid of your StreamWriter code entirely. If you're using File.AppendAllText, you don't need a StreamWriter - File.AppendAllText is self-contained.
You are never CLOSING the file. I would recommend the 'using' statement which will automatically close your file for you.
Replace this portion of your code:
StreamWriter file2 = new StreamWriter("Shortcut_Items.txt", true);
string path = "Shortcut_Items.txt";
string appendText = Environment.NewLine + tempPath + Environment.NewLine;
File.AppendAllText(path, appendText);
With this:
using(StreamWriter file2 = new StreamWriter("Shortcut_Items.txt", true))
{
//Do whatever you're going to do with the file
}
string path = "Shortcut_Items.txt";
string appendText = Environment.NewLine + tempPath + Environment.NewLine;
File.AppendAllText(path, appendText);

How to save and read text file using File.ReadAllText() from application startup?

I'm saving a text file at application startup and reading this text file from application startup.
This is not saving my file at application startup, what's wrong with this code?
Saving text file at application startup code.
private void Savebutton1_Click(object sender, EventArgs e)
{
StreamWriter sw = new StreamWriter(Application.StartupPath + "Book.txt", true);
string json = JsonConvert.SerializeObject(vals);
sw.Write(json);
MessageBox.Show("Book Saved Successfully", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
loading text file from application startup code.
string path = Path.Combine(Application.StartupPath, "ChequeBook.txt");
string textholder;
try
{
// Use StreamReader to consume the entire text file.
using (StreamReader reader = new StreamReader(path))
{
MessageBox.Show("Reached Here");
textholder = reader.ReadToEnd();
MessageBox.Show("Reached Here - 2");
}
if (textholder == string.Empty) {
return;
}
// Deserialise it from Disk back to a Dictionary
string jsonToRead = File.ReadAllText(textholder);
List<KeyValuePair<int, string>> myDictionaryReconstructed =
JsonConvert.DeserializeObject<List<KeyValuePair<int, string>>>(jsonToRead);
I wanted to save & write text file in application folder using File.CreateText method.
Found the First Answer:
This will write and save the text file in application folder.
using (StreamWriter sw = File.CreateText(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Book.txt")))
{
string json = JsonConvert.SerializeObject(vals);
sw.Write(json);
}
MessageBox.Show("Book Saved Successfully", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information);
I wanted to read the text file from application folder.
This will read the contents of the text file from application folder.
string jsonToRead = File.ReadAllText(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Book.txt"));

Moving files from one location to another

I'm trying to make this program that will move (cut and paste) all files from one directory (a folder) to another directory. In this example, I'm trying to move all the files that are inside the D:\Source folder (has a few files in it) to C:\Source folder (which has no files in it). When I run the program, I get this error.
http://s13.postimg.org/kuufg0gmu/error.jpg
Here is the full source code:
using System.IO;
namespace FileManager
{
public partial class Form1 : Form
{
string sourceDirectory = "";
//string destinationDirectory = #"C:\Destination";
string date = "";
string[] filePaths;
string destinationPath;
public Form1()
{
InitializeComponent();
}
private void buttonClean_Click(object sender, EventArgs e)
{
// Get source directory
sourceDirectory = textBoxDirectory.Text;
// Get date of files
date = textBoxDate.Text;
// Get file paths
if (Directory.Exists(sourceDirectory))
{
filePaths = Directory.GetFiles(#sourceDirectory, "*", SearchOption.AllDirectories);
foreach (string sourcePath in filePaths)
{
destinationPath = sourcePath.Remove(0, 1).Insert(0, "C");
File.Copy(sourcePath, destinationPath);
//MessageBox.Show(destinationPath);
}
}
else
{
MessageBox.Show("Directory does not exist.");
}
}
}
}
You need to check if destination directory exists than copy files otherwise first create destination directory.
foreach (string sourcePath in filePaths)
{
destinationPath = sourcePath.Remove(0, 1).Insert(0, "C");
if(!Directory.Exists(destinationPath))
Directory.CreateDirectory(destinationpath);
File.Copy(sourcePath, destinationPath);
//MessageBox.Show(destinationPath);
}
Exception clearly states that destinationPath is not valid. Make sure destinationPath exist as shown by #Mairaj then use File.Move to cut-paste. Complete code to move one file. You can your logic of directories to move all the files.
using System;
using System.IO;
class Test
{
public static void Main()
{
string path = #"c:\temp\MyTest.txt";
string path2 = #"c:\temp2\MyTest.txt";
try
{
if (!File.Exists(path))
{
// This statement ensures that the file is created,
// but the handle is not kept.
using (FileStream fs = File.Create(path)) {}
}
// Ensure that the target does not exist.
if (File.Exists(path2))
File.Delete(path2);
// Move the file.
File.Move(path, path2);
Console.WriteLine("{0} was moved to {1}.", path, path2);
// See if the original exists now.
if (File.Exists(path))
{
Console.WriteLine("The original file still exists, which is unexpected.");
}
else
{
Console.WriteLine("The original file no longer exists, which is expected.");
}
}
catch (Exception e)
{
Console.WriteLine("The process failed: {0}", e.ToString());
}
}
}
Find more info here

Opening text file in c#

When I try to open a .txt file it only shows its location in my textbox.
I am out of ideas:( hope you can help me...
code:
private void OpenItem_Click(object sender, EventArgs e)
{
openFileDialog1.ShowDialog();
System.IO.StringReader OpenFile = new System.IO.StringReader(openFileDialog1.FileName);
richTextBox1.Text = OpenFile.ReadToEnd();
OpenFile.Close();
}
A StringReader reads the characters from the string you pass to it -- in this case, the file's name. If you want to read the contents of the file, use a StreamReader:
var OpenFile = new System.IO.StreamReader(openFileDialog1.FileName);
richTextBox1.Text = OpenFile.ReadToEnd();
Use File.ReadAllText
richTextBox1.Text = File.ReadAllText(openFileDialog1.FileName);
I'd use the File.OpenText() method for reading text-files. You should also use using statements to properly dispose the object.
if(openFileDialog1.ShowDialog() == DialogResult.OK)
{
try
{
// Make sure a file was selected
if ((myStream = openFileDialog1.OpenFile()) != null) {
// Open stream
using (StreamReader sr = File.OpenText(openFileDialog1.FileName))
{
// Read the text
richTextBox1.Text = sr.ReadToEnd();
}
}
}
catch (Exception ex)
{
MessageBox.Show("An error occured: " + ex.Message);
}
}
That's easy. This is what you need to do:
1) Put using System.IO; above namespace.
2) Create a new method:
public static void read()
{
StreamReader readme = null;
try
{
readme = File.OpenText(#"C:\path\to\your\.txt\file.txt");
Console.WriteLine(readme.ReadToEnd());
}
// will return an invalid file name error
catch (FileNotFoundException errorMsg)
{
Console.WriteLine("Error, " + errorMsg.Message);
}
// will return an invalid path error
catch (Exception errorMsg)
{
Console.WriteLine("Error, " + errorMsg.Message);
}
finally
{
if (readme != null)
{
readme.Close();
}
}
}
3) Call it in your main method: read();
4) You're done!

C# linq Files.ReadAllLines() fails for large 650MB CSV file

The following code works when I work with CSV files under 1MB but fails when I try to read 600MB file. Any reason why? Or any fixes?
What I am trying to do is read a large raw CSV file in Visual C# 2010 and manipulate the contents, could be line by line or to memory at one go and export 5 files with certain selections using LINQ. These 5 files are to be used in various processes so need them to be split into 5 different files with very different content.
When the file is small the codes work perfect but when it's too big it gives me the messagebox from Exception handling "Cannot write to source destination". I have tried both ReadAllLines() and ReadLines() Please could you advise me. Thanks.
public void button2_Click(object sender, EventArgs e)
{
string file_name = textBox1.Text.ToString();
// Get the directories to split the file in.
string directoryPath = Path.GetDirectoryName(textBox1.Text.ToString());
if (File.Exists(file_name) == true)
{
try
{
StreamReader readerfile = new StreamReader(file_name);
var BillSummaryQuery1 =
(from line in File.ReadAllLines(file_name)
let linerecord = line.Split(',').ToList()
select line).ToList();
#region Start Writing BillSummary.CSV
//lines removed
#endregion End writing BillSummary.CSV
#region Start writing Notes.CSV
//lines removed
#endregion Notes.CSV
string message =
"Bill Translated Successfully! \r\nFiles located in: " + directoryPath;
MessageBox.Show(message, "Success", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
catch (Exception)
{
string message2 = "Cannot write to source destination";
MessageBox.Show(message2, "Error");
}
}
else
{
MessageBox.Show("No such file exists","Error",MessageBoxButtons.OK,MessageBoxIcon.Error);
}
If you are using a StreamReader, why don't use it ?
public void button2_Click(object sender, EventArgs e)
{
string file_name = textBox1.Text.ToString();
// Get the directories to split the file in.
string directoryPath = Path.GetDirectoryName(textBox1.Text.ToString());
if (File.Exists(file_name) == true)
{
try
{
using (StreamReader reader= new StreamReader(file_name))
{
string line = null;
while ((line = reader.ReadLine()) != null)
{
// Do your stuff
}
}
}
catch (Exception ex)
{
Trace.TraceError(ex.Message);
string message2 = "Cannot write to source destination";
MessageBox.Show(message2, "Error");
}
}
else
{
MessageBox.Show("No such file exists", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
Rolling your own CSV reader is a waste of time unless the files that you're reading are guaranteed to be very simple. Use a pre-existing, tried-and-tested implementation instead.

Categories