FileSystemWatcher works 3-5 times before throwing exceptions - C# - c#

File comes in over EDI as .today. I need to change it to .txt and move it to another folder. Everything works just fine for about 3-5 files, then starts throwing exceptions. I tried handling those, but that doesn't solve the problem. I'm also getting sporadic (filename cannot be null) exceptions as well. I just can't seem to figure this out.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.Diagnostics;
using System.Threading;
using System.Windows.Forms;
using System.Security.Permissions;
namespace FileConverterService
{
class ConverterService
{
//Configure watcher & input
private FileSystemWatcher _watcher;
public bool Start()
{
_watcher = new FileSystemWatcher(#"C:\FTP_base\temp", "*.today");
_watcher.Created += new FileSystemEventHandler(FileCreated);
_watcher.IncludeSubdirectories = false;
_watcher.EnableRaisingEvents = true;
return true;
}
//Configure output creation and append file name to include .txt extension
[PermissionSet(SecurityAction.Demand, Name = "FullTrust")]
private void FileCreated(object sender, FileSystemEventArgs e)
{
try
{
string dateTime = DateTime.Now.ToString("yyyyMMddHHmmssfff");
string content = File.ReadAllText(e.FullPath);
string upperContent = content.ToUpperInvariant();
var dir = Path.GetDirectoryName(e.FullPath);
var convertedFileName = Path.GetFileName(e.FullPath) + dateTime + ".txt";
var convertedPath = Path.Combine(dir, convertedFileName);
File.WriteAllText(convertedPath, upperContent);
}
catch (IOException f)
{
if (f is IOException)
{
MessageBox.Show("Exception Caught"); //was just testing
}
}
MoveConvert();
}
//Move converted file to EDI processing folder
public static void MoveConvert()
{
try {
string dateTime = DateTime.Now.ToString("yyyyMMddHHmmssfff");
string rootFolderPath = #"C:\FTP_base\temp\";
string moveTo = #"C:\FTP_base\INbound\inbound_" + dateTime + ".txt";
//string moveTo = #"F:\FTP_base\Office Depot\INbound\inbound_" + dateTime + ".txt";
string filesToMove = #"*.txt"; // Only move .txt
string myfile2 = System.IO.Directory.GetFiles(rootFolderPath, filesToMove).FirstOrDefault();
string fileToMove = myfile2;
//moving file
File.Move(fileToMove, moveTo);
MoveOriginal();
}
catch (IOException e)
{
if (e is IOException)
{
MessageBox.Show("File already exists."); //was just testing
}
}
}
public static void MoveOriginal()
{
try {
string dateTime = DateTime.Now.ToString("yyyyMMddHHmmssfff");
string rootFolderPath2 = #"C:\FTP_base\temp\";
string moveTo2 = #"C:\FTP_base\archive\archive_" + dateTime + ".archive";
//string moveTo2 = #"F:\Xcelerator_EDI\OfficeDepot\DataFiles\Inbound\Archive2\archive_" + dateTime + ".archive";
string filesToMove2 = #"*.today"; // Only move .today
string myfile = System.IO.Directory.GetFiles(rootFolderPath2, filesToMove2).FirstOrDefault();
//foreach (string file in fileList)
string fileToMove2 = myfile;
//moving file
File.Move(fileToMove2, moveTo2);
}
catch (IOException e)
{
if (e is IOException)
{
MessageBox.Show("IO Exception Occurred"); //was just testing
}
}
}
//Stop Service control
public bool Stop()
{
_watcher.Dispose();
return true;
}
}
}

Perhaps the files are still in use. The FileSystemWatcher event is raised when a file is created, but the creating process can still be writing to it. See here for a possible solution.

Related

Sorting excel sheets c# || how to exclude lines that are missing a specific cell

I am currently working on a windows forms app using c# that will be able to convert Pastel Partner trial balances to Pastel Evolution compatible balances.
I am trying to implement code that will skip all lines in the sheet that do not have account codes (col 2)
Please assist with a code example on how to do this, it would be highly appreciated!
The excel sheet needs to convert from this (Partner)...
To this (Evolution)...
This is my form and code so far...
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Evo_Mod
{
public partial class Form1 : Form
{
public string date; // set by user
public string codeDate; // set by date and OB string
public string OB = "OB"; // set value
public string zero = "0"; // set value
public string accCode; // needs to be read from the first excell sheet and printed with a ">"
public string contraCode = "9990>001"; // set value
public bool credCheck = false; // bool that is interactive
public bool debCheck = false; // bool that is interactive depending on whether the account is in credit or debit
public string fileName = ""; // set from the openFileDialog
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e) // lets user select csv file.
{
openFileDialog1.ShowDialog();
openFileDialog1.Filter = "CSV Files (L*.csv)|L*.csv"; // Filters to only .csv files
fileName = openFileDialog1.FileName;
if(openFileDialog1.ShowDialog() == DialogResult.OK)
{
lblFileName.Text = openFileDialog1.FileName; // prints file directory
}
}
public static string[] ReadCSV(string searchTerm , string filePath , int positionOfSearch)
{
positionOfSearch--; // moves over by 1 (more understandable)
string[] recordNotFound = { " Record Not Found " }; // array for errors
try
{
string[] lines = System.IO.File.ReadAllLines(#filePath);
for (int i = 0; i < lines.Length; i++)
{
string[] fields = lines[i].Split(',');
if (recordMatches(searchTerm , fields , positionOfSearch))
{
return fields;
}
}
return recordNotFound;
}
catch(Exception ex)
{
Console.WriteLine("error");
return recordNotFound;
throw new ApplicationException("Error : ", ex);
}
}
public static bool recordMatches(string searchTerm , string[] record , int positionOfSearch)
{
if (record[positionOfSearch] != " ")
{
return true;
}
return false;
}
private void btnConvert_Click(object sender, EventArgs e)
{
DateTime tempDate = dateTimePicker1.Value;
codeDate = "OB " + tempDate.ToString("dd/MM/yyyy");
date = tempDate.ToString("dd/MM/yyyy");
}
}
}
If the account codes are in col 2, then you can check for empty values in the loop which you already have
string[] fields = lines[i].Split(',');
if (fields[1] != "") <-- check if account code is an empty string
{
if (recordMatches(searchTerm , fields , positionOfSearch))
{
...

C# Connect via SSH and changing the file content

I am a C # amateur I am not a professional developer and would like to ask my colleagues for help, I would like to make a C # program that connects to an SSH server. Then, depending on the selected value in combobox, the program downloads the appropriate string and I would like to send it to the ssh server to the specified path path and save the value from the string to the file;)
I tried to rewrite the code but something did not work out and I stopped in my place ;( Can anyone help me. Thanks in advance for your help.
this is my code
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Threading;
using Renci.SshNet;
namespace FileGenerator
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void btnConnect_Click(object sender, EventArgs e)
{
SshClient sshClient = new SshClient("192.168.1.22", 22, "root", "pass");
sshClient.ConnectionInfo.Timeout = TimeSpan.FromSeconds(120);
sshClient.Connect();
ShellStream shellStreamSSH = sshClient.CreateShellStream("vt-100", 80, 60, 800, 600, 65536);
Thread thread = new Thread(() => recvSSHData(shellStreamSSH));
thread.Start();
//I don't know how to get the information if it is connected correctly and change e.g. btnConnect label to Connected.
}
public static void recvSSHData(ShellStream shellStreamSSH)
{
while (true)
{
try
{
if (shellStreamSSH != null && shellStreamSSH.DataAvailable)
{
string strData = shellStreamSSH.Read();
}
}
catch
{
}
System.Threading.Thread.Sleep(200);
}
}
string data1 = "data1";
string data2 = "data2";
string data3 = "data3";
string check;
string path = "/home/test01/desktop";
string filename = "test.txt";
private void btnSend_Click(object sender, EventArgs e)
{
if (cmbData.SelectedIndex == 0)
{
check = data1;
MessageBox.Show(check);
}
else if (cmbData.SelectedIndex == 1)
{
check = data2;
MessageBox.Show(check);
}
else if (cmbData.SelectedIndex == 2)
{
check = data3;
MessageBox.Show(check);
}
else
{
MessageBox.Show("Choose a value");
}
//And now there should be an instruction that sends a string check to the server to path to file replacing its contents
}
}
}
Ok, I coped with everything but I am on the last step, how to save the contents of string to a file using client scp ??
string text= "bal bla bla bla bla"
string path = "#/home/test01/desktop/";
string filename = "test1.txt"
...
try
{
MemoryStream mStrm = new MemoryStream(Encoding.UTF8.GetBytes(text));
scpClient.Upload(mStrm, path + filename);
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
I have error:
Renci.SshNet.Common.ScpException: scp: error: unexpected filename:
w Renci.SshNet.ScpClient.CheckReturnCode(Stream input)
w Renci.SshNet.ScpClient.UploadFileModeAndName(IChannelSession channel, Stream input, Int64 fileSize, String serverFileName)
w Renci.SshNet.ScpClient.Upload(Stream source, String path)
w FileGenerator.Form1.btnSend_Click(Object sender, EventArgs e) w C:\Users\backu\source\repos\FileGenerator\FileGenerator\Form1.cs:wiersz 192

Code not executing correctly in windows forms app

I'm trying to make a windows form application to do the same thing that I have a console application doing. The design is just a box with two labels (going to try to add a progress bar later on) but for some reason the code is not working correctly.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Diagnostics;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Windows.Forms;
namespace WindowsFormsApp1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void label1_Click(object sender, EventArgs e)
{
}
private void Form1_Load(object sender, EventArgs e)
{
string date = DateTime.Now.ToString("ddMMyy");
string Source = #"G:\Personal\A1";
string Destination = #"D:\_Lil USB Backup\" + "b";
if (System.IO.Directory.Exists(Source))
{
if (System.IO.Directory.Exists(Destination))
{
infoBox.Text = "Backup already exists for today. U rem";
}
else
{
System.IO.Directory.CreateDirectory(Destination);
}
try
{
CopyAllFiles(Source, Destination);
infoBox.Text = "Files backed up successfully.";
if (System.IO.Directory.Exists(#"D:\" + date + #"System Volume Information"))
{
Directory.Delete(#"D:\" + date + #"System Volume Information", true);
infoBox.Text = "Files backed up successfully.\n System Volume Information folder deleted.\n Backup successfull.";
}
else
{
infoBox.Text = "System Volume Information folder does not exist and therefore was not deleted.\n Backup successfull.";
}
}
catch (Exception ez)
{
infoBox.Text = "Umm, something didn't work. Oh maybe it was this? " + ez.Message;
}
}
else
{
infoBox.Text = "Source does not exist, try plugging the USB in dipshit.";
}
}
private static void CopyAllFiles(string Source, string Destination)
{
try
{
// Get the subdirectories for the specified directory.
DirectoryInfo dir = new DirectoryInfo(Source);
DirectoryInfo[] dirs = dir.GetDirectories();
if (!dir.Exists)
{
Label infoBoxErr = new Label();
infoBoxErr.Text = "Directory could not be found.";
}
// If the destination directory doesn't exist, create it.
if (!Directory.Exists(Destination))
{
Directory.CreateDirectory(Destination);
}
// Get the files in the directory and copy them to the new location.
FileInfo[] files = dir.GetFiles();
foreach (FileInfo file in files)
{
string temppath = Path.Combine(Destination, file.Name);
file.CopyTo(temppath, true);
}
foreach (DirectoryInfo subdir in dirs)
{
string temppath = Path.Combine(Destination, subdir.Name);
CopyAllFiles(subdir.FullName, temppath);
}
}
catch (Exception ex)
{
Label infoBoxErr = new Label();
infoBoxErr.Text = "Oh. Something didn't work, sorry. Might have been this: " + ex.Message + " lol!";
}
}
private void progressBar1_Click(object sender, EventArgs e)
{
}
}
}
The problem is that it outputs the text in the labels as expected as if it was successful. Yet it does not create a new folder or copy any of the files. I have no idea why and it's not giving me any errors!
First of all you catch exception within CopyAllFiles method. And its code
catch (Exception ex)
{
Label infoBoxErr = new Label();
infoBoxErr.Text = "Oh. Something didn't work, sorry. Might have been this: " + ex.Message + " lol!";
}
doesn't do anything because it creates label infoBoxErr in memory and doesn't display it at all.
So, the following code
try
{
CopyAllFiles(Source, Destination);
infoBox.Text = "Files backed up successfully.";
if (System.IO.Directory.Exists(#"D:\" + date + #"System Volume Information"))
{
Directory.Delete(#"D:\" + date + #"System Volume Information", true);
infoBox.Text = "Files backed up successfully.\n System Volume Information folder deleted.\n Backup successfull.";
}
else
{
infoBox.Text = "System Volume Information folder does not exist and therefore was not deleted.\n Backup successfull.";
}
}
catch (Exception ez)
{
infoBox.Text = "Umm, something didn't work. Oh maybe it was this? " + ez.Message;
}
never reaches the catch block (because of inner catch in CopyAllFiles method) and just displays success text.
So I'd suggest you to remove that inner catch and see what happens.

File I/O Exceptions

i am currently working on a Windows Forms App in c# which will allow the user to add or delete records. when i hit the button to display all the records written to the file the files appear, but when i try to delete by transact number i get an exception saying that "The process cannot access the the because it is being used somewhere else". i have tried putting it in a try-catch block to make sure the reader/writer will close and still not working code will be attached any help is greatly appreciated. p.s im not looking for code to finish this project just help getting by this exception and make it work like it is suppose.
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.Threading.Tasks;
using System.Windows.Forms;
namespace MMFileIO
{
public partial class MMAssignment3 : Form
{
StreamWriter writer;
StreamReader reader;
string record = "";
public MMAssignment3()
{
InitializeComponent();
}
private void MMAssignment3_Load(object sender, EventArgs e)
{
txtFile.Text = #"c:\burnable\assignment3.txt";
if (!Directory.Exists(txtFile.Text.Substring
(0, txtFile.Text.LastIndexOf('\\'))))
MessageBox.Show("File path does not exist");
}
private void btnAdd_Click(object sender, EventArgs e)
{
try
{
if (radNew.Checked)
writer = new StreamWriter(txtFile.Text, append: false);
else
writer = new StreamWriter(txtFile.Text, append: true);
}
catch(Exception ex)
{
if (writer != null)
writer.Close();
MessageBox.Show($"exception adding new record: {ex.Message}");
return;
}
record = $"{txtTransact.Text}::{txtDate.Text}::{txtSerial.Text}::" +
$"{txtToolPurchased.Text}::${txtPrice.Text}::{txtQty.Text}::" +
$"${txtAmount.Text}";
try
{
writer.WriteLine(record);
lblMessage.Text = ($"Record added");
txtTransact.Text = txtDate.Text = txtSerial.Text =
txtToolPurchased.Text = txtPrice.Text = txtQty.Text =
txtAmount.Text = "";
}
catch(Exception ex)
{
MessageBox.Show($"exception adding a new record: {ex.Message}");
}
finally
{
writer.Close();
}
}
private void btnDelete_Click(object sender, EventArgs e)
{
reader = new StreamReader(txtFile.Text);
List<string> records = new List<string>();
while (! reader.EndOfStream)
{
record = reader.ReadLine();
records.Add(record);
}
if (records.Count == 0)
MessageBox.Show("No records left in file");
reader.Close();
writer = new StreamWriter(txtFile.Text, append: false);
foreach (string item in records)
{
}
}
private void btnCloseFile_Click(object sender, EventArgs e)
{
txtDataDisplay.Text = "";
reader.Close();
}
private void btnDisplay_Click(object sender, EventArgs e)
{
reader = new StreamReader(txtFile.Text);
txtDataDisplay.Text = $"{"#".PadRight(10)}\t" +
$"{"Purchase-Date".PadRight(10)}\t{"Serial #".PadRight(10)}\t" +
$"{"Manufacturing Tools".PadRight(10)}\t{"Price".PadRight(10)}\t" +
$"{"Qty".PadRight(10)}\t{"Amount".PadRight(10)}\n{"".PadRight(50)}\n";
while (!reader.EndOfStream)
{
record = reader.ReadLine();
string[] fields = record.Split(new string[] { "::" }, StringSplitOptions.None);
txtDataDisplay.Text += $"{fields[0].PadRight(10)}\t" +
$"{fields[1].PadRight(10)}\t{fields[2].PadRight(10)}\t" +
$"{fields[3].PadRight(30)}\t{fields[4].PadRight(10)}\t" +
$"{fields[5].PadRight(10)}\t{fields[6].PadRight(10)}\n";
}
reader.Close();
}

Auto find files, pass to connection string and read

Firstly, I would just like to add that I am an absolute beginner at C#, I'm doing my best to learn so I am sorry if this is a noob question, but I have hit a brick wall.
I am working on a program that when finished it will find .DBF files from a specified folder, read the file and insert into a mysql database. I am stuck pretty much at the first hurdle.
I am trying to make the program loop through each file it finds and read them.
I can't seem to be able to access the filename string from the GetFiles() Void.
Is there another way around passing the filename to the queryString rather than specifying it myself?
here is my code -
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Data.OleDb;
namespace WindowsApplication4
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
//OPEN PROGRAM
private void Form1_Load(object sender, EventArgs e)
{
this.richTextBox1.Text = "Waiting for commands...";
this.toolStripStatusLabel1.Text = "Waiting for commands...";
}
// FIND FILES BUTTON CLICK
private void button1_Click(object sender, EventArgs e)
{
this.richTextBox1.Text = "Looking for files...";
GetFiles();
}
// function to read files at source
private void GetFiles()
{
List<String> Myfiles = new List<string>();
string[] allFiles = System.IO.Directory
.GetFiles(#"C:\Users\74-des\Desktop\", "*.DBF");
if (allFiles.Length > 0)
{
try
{
foreach (string filename in allFiles)
{
this.richTextBox1.Text = string.Join(Environment.NewLine,allFiles);
string filenameWithoutPath = Path.GetFileName(filename);
}
}
catch (SystemException excpt)
{
this.richTextBox1.Text = excpt.Message;
}
}
}
private void ReadData()
{
this.toolStripStatusLabel1.Text = "Preparing To Read Data";
this.Refresh();
DirectoryInfo dir = new DirectoryInfo(#"C:\Users\74-des\Desktop\");
string connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + dir + ";Extended Properties=dBase IV";
string queryString = "SELECT * FROM " + "test4.DBF";
try
{
using (OleDbConnection connection = new OleDbConnection(connectionString))
{
OleDbCommand command = new OleDbCommand(queryString, connection);
connection.Open();
OleDbDataReader reader = command.ExecuteReader();
while (reader.Read())
{
if (reader.IsDBNull(1))
{
this.richTextBox1.Text = "Null";
}
else
{
string DATE = reader.GetValue(0).ToString();
string TIME = reader.GetValue(1).ToString();
string CODE = reader.GetValue(2).ToString();
string item = reader.GetValue(3).ToString();
this.richTextBox1.Text = DATE + TIME + " " + CODE + " " + item;
this.Refresh();
}
}
reader.Close();
connection.Close();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void button2_Click(object sender, EventArgs e)
{
ReadData();
}
}
}
you can do the following
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Data.OleDb;
namespace WindowsApplication4
{
public partial class Form1 : Form
{
private string mDirectory; // this will hold the directory path you are working on
private string[] mFiles; // this will hold all files in the selected directory
public Form1()
{
InitializeComponent();
}
//OPEN PROGRAM
private void Form1_Load(object sender, EventArgs e)
{
this.richTextBox1.Text = "Waiting for commands...";
this.toolStripStatusLabel1.Text = "Waiting for commands...";
}
// FIND FILES BUTTON CLICK
private void button1_Click(object sender, EventArgs e)
{
this.richTextBox1.Text = "Looking for files...";
GetFiles();
}
// function to read files at source
private void GetFiles()
{
mDirectory = #"C:\Users\74-des\Desktop\"; // better to use OpenFolderDialog to choose the directory
mFiles = System.IO.Directory.GetFiles(mDirectory, "*.DBF");
if (mFiles.Length > 0)
{
try
{
foreach (string filename in mFiles)
{
this.richTextBox1.Text = string.Join(Environment.NewLine, mFiles);
string filenameWithoutPath = System.IO.Path.GetFileName(filename);
}
}
catch (SystemException excpt)
{
this.richTextBox1.Text = excpt.Message;
}
}
}
private void ReadData()
{
this.toolStripStatusLabel1.Text = "Preparing To Read Data";
this.Refresh();
string connectionString = string.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=dBase IV", mDirectory);
try
{
foreach (var file in mFiles)
{
string queryString = string.Format("SELECT * FROM " + "{0}.DBF", System.IO.Path.GetFileNameWithoutExtension(file));
using (OleDbConnection connection = new OleDbConnection(connectionString))
{
OleDbCommand command = new OleDbCommand(queryString, connection);
connection.Open();
OleDbDataReader reader = command.ExecuteReader();
while (reader.Read())
{
if (reader.IsDBNull(1))
{
this.richTextBox1.Text = "Null";
}
else
{
string DATE = reader.GetValue(0).ToString();
string TIME = reader.GetValue(1).ToString();
string CODE = reader.GetValue(2).ToString();
string item = reader.GetValue(3).ToString();
this.richTextBox1.Text = DATE + TIME + " " + CODE + " " + item;
this.Refresh();
}
}
reader.Close();
connection.Close();
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void button2_Click(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(mDirectory))
MessageBox.Show("You should Get Files first!");
else
ReadData();
}
}
}
hope it will help you

Categories

Resources