Listing all the files in root directory - c#

Thanks for your support! I now have working code to scan all folders, subfolders and files. There is just one problem left to solve:
I do not get the files in the initial root directory, only the subfolders. I also need to call FileInfo for these files.
How could this be resolved without modifying the code too much?
private void ScanFolder(String prefix, String path)
{
try
{
string user = System.IO.File.GetAccessControl(path).GetOwner(typeof(System.Security.Principal.NTAccount)).ToString();
DirectoryInfo di = new DirectoryInfo(path);
foreach (var dir in new DirectoryInfo(path).GetDirectories("*", SearchOption.TopDirectoryOnly))
{
listBox1.Invoke((MethodInvoker)delegate { listBox1.Items.Add(prefix + dir.Name + " (" + dir.Name.Length.ToString() + ") "); });
foreach (FileInfo fileInfo in dir.GetFiles())
{
listBox1.Invoke((MethodInvoker)delegate { listBox1.Items.Add(prefix + fileInfo.Name + " (" + fileInfo.Name.Length.ToString() + ") " + user + " " + fileInfo.FullName + " (" + fileInfo.FullName.Length.ToString() + ")"); });
}
ScanFolder(prefix + "—", dir.FullName);
}
}
catch
{
if (!this.IsDisposed)
{
listBox1.Invoke((MethodInvoker)delegate { listBox1.Items.Add("Access Denied to : " + path); });
}
}
}
Output:
** The files should be here **
13-9-legacy_vista_win7_64_dd_ccc_whql (37)
Radeon-Software-Adrenalin-18.3.3-MinimalSetup-180319_web (56)
—Bin (3)
——localization (12)
———cs (2)
———da_DK (5)
———de (2)
———el_GR (5)
———es_ES (5)

So far you're only looking for the directories in the root directory.
You also want to enumerate through the files though:
private void ScanFolder(String prefix, String path)
{
try
{
string user = System.IO.File.GetAccessControl(path).GetOwner(typeof(System.Security.Principal.NTAccount)).ToString();
DirectoryInfo di = new DirectoryInfo(path);
// Enumerate through the files here
foreach (FileInfo fileInfo in di.GetFiles())
{
listBox1.Invoke((MethodInvoker)delegate { listBox1.Items.Add(prefix + fileInfo.Name + " (" + fileInfo.Name.Length.ToString() + ") " + user + " " + fileInfo.FullName + " (" + fileInfo.FullName.Length.ToString() + ")"); });
}
// ----
// You can also use the DirectoryInfo you created earlier here
foreach (var dir in new di.GetDirectories("*", SearchOption.TopDirectoryOnly))
{
listBox1.Invoke((MethodInvoker)delegate { listBox1.Items.Add(prefix + dir.Name + " (" + dir.Name.Length.ToString() + ") "); });
foreach (FileInfo fileInfo in dir.GetFiles())
{
listBox1.Invoke((MethodInvoker)delegate { listBox1.Items.Add(prefix + fileInfo.Name + " (" + fileInfo.Name.Length.ToString() + ") " + user + " " + fileInfo.FullName + " (" + fileInfo.FullName.Length.ToString() + ")"); });
}
ScanFolder(prefix + "—", dir.FullName);
}
}
catch
{
if (!this.IsDisposed)
{
listBox1.Invoke((MethodInvoker)delegate { listBox1.Items.Add("Access Denied to : " + path); });
}
}
}

Related

Encoding missing from reading file

Hello i'm developing a little application that download attachment from unread mails by imap and make a sevarla job on this attachment. Problem is encoding because after i have saved a, for example, txt file, when i load it again letters with accents becomes "?" I dont know why. I tried a several example around on the web (like converting directly the file from ansi to utf-8) with no result. Whe i open a file in windows it works, words are correct.
i have used either ReadAllText that StreamReader in the following example:
string contents = File.ReadAllText(AppDomain.CurrentDomain.BaseDirectory + "\\uid\\" + summary.UniqueId.ToString() + "\\" + fileName, Encoding.UTF8);
using (StreamReader reader = new StreamReader(contents, Encoding.UTF8))
as you can see in the following example if i set directly a string with an accent word, it works, from file no.
Please help me!
check image
Reproducible Code:
using CsvHelper;
using NLog;
using System;
using System.Data;
using System.IO;
using System.Text;
namespace ConsoleApp1
{
class Class1
{
public static void test2()
{
using (var client = new ImapClient())
{
try
{
int porta = Convert.ToInt32(par.portaimap);
bool ssl = Convert.ToBoolean(par.sslimap);
client.Connect(par.host, porta, ssl);
Logger.Info("Connessione server posta riuscita");
}
catch (Exception ex)
{
Logger.Error("Connessione non riuscita; di seguito l'errore: " + ex.Message);
}
try
{
Logger.Info("Autenticazione in corso");
client.Authenticate(par.usernameimap, par.passwordimap);
}
catch (Exception ex)
{
Logger.Error("Connessione non riuscita; di seguito l'errore: " + ex.Message);
}
// The Inbox folder is always available on all IMAP servers...
var inbox = client.Inbox;
inbox.Open(FolderAccess.ReadWrite);
Console.WriteLine("Total messages: {0}", inbox.Count);
Console.WriteLine("Recent messages: {0}", inbox.Recent);
var query = SearchQuery.NotSeen;//SearchQuery.SubjectContains("MimeKit").Or(SearchQuery.SubjectContains("MailKit"));
var uids = client.Inbox.Search(query);
var items = client.Inbox.Fetch(uids, MessageSummaryItems.UniqueId | MessageSummaryItems.BodyStructure);
Logger.Info("Selezione lista di email non lette");
foreach (var summary in items)
{
var directory = Path.Combine(AppDomain.CurrentDomain.BaseDirectory + "\\uid\\", summary.UniqueId.ToString());
// create the directory
Directory.CreateDirectory(directory);
if (summary.Body is BodyPartMultipart)
Logger.Info("Download allegati in corso.");
foreach (var attachment in summary.Attachments)
{
var entity = client.Inbox.GetBodyPart(summary.UniqueId, attachment);
var part = (MimePart)entity;
// note: it's possible for this to be null, but most will specify a filename
var fileName = part.FileName;
var path = Path.Combine(directory, fileName);
try
{
using (var stream = File.Create(path))
part.Content.DecodeTo(stream);
Logger.Info("Allegato scaricato.");
}
catch (Exception ex)
{
Logger.Error("Allegato non scaricato. Di seguito errore: " + ex.Message);
}
int scelta = 0;
string contents = File.ReadAllText(AppDomain.CurrentDomain.BaseDirectory + "\\uid\\" + summary.UniqueId.ToString() + "\\" + fileName, Encoding.UTF8);
Console.WriteLine(contents);
Console.ReadLine();
contents = "Proprietà";
Console.WriteLine(contents);
Console.ReadLine();
string ext = Path.GetExtension(fileName);
SmtpSettings smtpSettings = new SmtpSettings();
smtpSettings.SenderName = "Test";
smtpSettings.server = "smtp.gmail.com";
smtpSettings.Port = 587;
smtpSettings.SenderMail = par.usernameimap;
smtpSettings.Username = par.usernameimap;
smtpSettings.Password = par.passwordimap;
smtpSettings.ToMail1Name = "Test1";
smtpSettings.ToMail1 = "test1#gmail.com";
smtpSettings.ToMail2Name = "Test2";
smtpSettings.ToMail2 = "Test2#bsolution.org";
string PATHTODELETE = "";
if (ext == ".txt")
{
string line1 = File.ReadLines(AppDomain.CurrentDomain.BaseDirectory + "\\uid\\" + summary.UniqueId.ToString() + "\\" + fileName).First();
if (line1 == "FOR|CLIEN|STAB|INSEGNA|INDIRIZZO|CAP|LUOGO|PROV|ORDINE|POS|STATO|DTORD|ORAORD|MALFUNZIONE|COD_RIS|RISORSA|TERMID|ESESIA|STABSIA|ABI|TELEFONO|NOTE|COD_HOST|ACCESSORIO|DESC_HOST|MOD_COLLEG|FUNZ. AGG:|REFERENTE|DT_SCADENZA|LAKA|")
{
DataTable dt;
using (StreamReader reader = new StreamReader(contents, Encoding.UTF8))
using (var csv = new CsvReader(reader, CultureInfo.InvariantCulture))
{
csv.Configuration.Delimiter = "|";
// Do any configuration to `CsvReader` before creating CsvDataReader.
using (var dr = new CsvDataReader(csv))
{
dt = new DataTable();
dt.Load(dr);
reader.Close();
}
}
//Costruzione body mail csv
string value = "";
string filename = "";
string Msg = "";
foreach (DataRow drow in dt.Rows)
{
value = "";
value += "FOR: " + drow["FOR"].ToString() + "\n";
value += "CLIEN: " + drow["CLIEN"].ToString() + "\n";
value += "STAB: " + drow["STAB"].ToString() + "\n";
value += "INSEGNA: " + drow["INSEGNA"].ToString() + "\n";
value += "INDIRIZZO: " + drow["INDIRIZZO"].ToString() + "\n";
value += "LUOGO: " + drow["LUOGO"].ToString() + "\n";
value += "ORDINE: " + drow["ORDINE"].ToString() + "\n";
value += "POS: " + drow["POS"].ToString() + "\n";
value += "STATO: " + drow["STATO"].ToString() + "\n";
value += "DTORD: " + drow["DTORD"].ToString() + "\n";
value += "ORAORD: " + drow["ORAORD"].ToString() + "\n";
value += "MALFUNZIONE: " + drow["MALFUNZIONE"].ToString() + "\n";
value += "COD_RIS: " + drow["COD_RIS"].ToString() + "\n";
value += "RISORSA: " + drow["RISORSA"].ToString() + "\n";
value += "TERMID: " + drow["TERMID"].ToString() + "\n";
value += "ESESIA: " + drow["ESESIA"].ToString() + "\n";
value += "STABSIA: " + drow["STABSIA"].ToString() + "\n";
value += "ABI: " + drow["ABI"].ToString() + "\n";
value += "TELEFONO: " + drow["TELEFONO"].ToString() + "\n";
value += "NOTE: " + drow["NOTE"].ToString() + "\n";
value += "COD_HOST: " + drow["COD_HOST"].ToString() + "\n";
value += "ACCESSORIO: " + drow["ACCESSORIO"].ToString() + "\n";
value += "DESC_HOST: " + drow["DESC_HOST"].ToString() + "\n";
value += "MOD_COLLEG: " + drow["MOD_COLLEG"].ToString() + "\n";
value += "FUNZ. AGG: " + drow["FUNZ. AGG:"].ToString() + "\n";
value += "REFERENTE: " + drow["REFERENTE"].ToString() + "\n";
value += "DT_SCADENZA: " + drow["DT_SCADENZA"].ToString() + "\n";
value += "LAKA: " + drow["LAKA"].ToString();
Msg = value;
// Save File to .txt
filename = AppDomain.CurrentDomain.BaseDirectory + "\\uid\\" + summary.UniqueId.ToString() + "\\" + DateTime.Now.Millisecond.ToString() + ".txt";
PATHTODELETE = AppDomain.CurrentDomain.BaseDirectory + "\\uid\\" + summary.UniqueId.ToString() + "\\";
using (FileStream fParameter = new FileStream(filename, FileMode.Create, FileAccess.Write))
{
StreamWriter m_WriterParameter = new StreamWriter(fParameter);
m_WriterParameter.BaseStream.Seek(0, SeekOrigin.End);
m_WriterParameter.Write(Msg, Encoding.UTF8);
m_WriterParameter.Flush();
m_WriterParameter.Close();
}
smtpSettings.Subject = "Oggetto Temporaneo da cambiare";
Invio(smtpSettings, Msg, filename);
try
{
inbox.AddFlags(summary.UniqueId, MessageFlags.Seen, true);
}
catch (Exception ex)
{
Logger.Error(ex.Message);
}
}
Logger.Info("Pulizia directory allegati in corso...");
DeleteDirectory(PATHTODELETE);
Logger.Info("Pulizia directory allegati terminata.");
}
else
{
string[] stringSeparators = new string[] { "************************************************************************************************************" };
string[] attivita = contents.Split(stringSeparators, StringSplitOptions.None);
foreach (string att in attivita)
{
Console.WriteLine(att);
string Msg = att;
// Save File to .txt
string filename = AppDomain.CurrentDomain.BaseDirectory + "\\uid\\" + summary.UniqueId.ToString() + "\\" + DateTime.Now.Millisecond.ToString() + ".txt";
PATHTODELETE = AppDomain.CurrentDomain.BaseDirectory + "\\uid\\" + summary.UniqueId.ToString() + "\\";
FileStream fParameter = new FileStream(filename, FileMode.Create, FileAccess.Write);
StreamWriter m_WriterParameter = new StreamWriter(fParameter);
m_WriterParameter.BaseStream.Seek(0, SeekOrigin.End);
m_WriterParameter.Write(Msg);
m_WriterParameter.Flush();
m_WriterParameter.Close();
smtpSettings.Subject = "Oggetto Temporaneo da cambiare";
if (att.Contains("OGGETTO"))
{
Invio(smtpSettings, att, filename);
}
else { }
}
Logger.Info("Pulizia directory allegati in corso...");
DeleteDirectory(PATHTODELETE);
try
{
inbox.AddFlags(summary.UniqueId, MessageFlags.Seen, true);
}
catch (Exception ex)
{
Logger.Error(ex.Message);
}
Logger.Info("Pulizia directory allegati terminata.");
}
}
else
{
}
}
}
}
}
}
}
After searching around on the web i found a solution, here microsoft msdn
Streamreader and maybe readalltext doesn't support accent letters with UTF-8 Encoding, so changing it in UTF-7, letters are showed correctly.
Thank you for all support!

Deleting files inside folder in C#

I am creating application to delete files for more than 15 days in past, I've created a project using the C# language "multithreading" to be able to delete these files, but its only reading the first file with the error
The directory name is invalid
Can anyone help me on this please?
private void process3()
{
//DirectoryInfo info1 = new DirectoryInfo(#"\\10.4.9.202\d\PapyrusRes\appdata\");
DirectoryInfo info1 = new DirectoryInfo(#"\\DXB-RASO-MCH\Users\oalahmad\Dropbox\backup\Backup5\Desktop\New folder2");
// long Size = 0;
//C:\Users\oalahmad\Dropbox\backup\Backup5\Desktop\New folder2
String[] filePaths = (from fls in info1.EnumerateFiles()
where (fls.LastWriteTime.Date < DateTime.Today.AddDays(-15))
select fls.FullName).ToArray();
int i = 0;
if (!File.Exists(logPath3))
{
// Create a file to write to.
using (StreamWriter sw = File.CreateText(logPath3))
{
sw.WriteLine("Deletion Process History:");
sw.WriteLine(" ");
sw.WriteLine(" ");
}
}
//stopwatch.Start();
try
{
foreach (String f in filePaths)
{
DirectoryInfo info = new DirectoryInfo(f);
int difference = DateTime.Today.Subtract(info.LastWriteTime).Days;
textBox2.BeginInvoke(new Action(() =>
{
textBox2.Text += "Folder Name: " + Path.GetFileName(f) +
"\r\nDate Modified: " + difference +
"\r\n------\r\n";
}));
Thread.Sleep(10);
i++;
Directory.Delete(f, true);
count++;
}
using (StreamWriter sw = File.AppendText(logPath3))
{
sw.WriteLine("Successful at: " + DateTime.Now + " " + count +
" files were deleted");
}
}
catch (Exception ex)
{
// log errors
// Write your content here
using (StreamWriter sw = File.AppendText(logPath3))
{
if (count == 0)
sw.WriteLine("Unsuccessful at: " + DateTime.Now + " Error: " +
ex.Message);
else
sw.WriteLine("Unsuccessful at: " + DateTime.Now + " " + count +
" files were deleted" + " Error: " + ex.Message);
}
}
}

GetFiles of certain extension and write to spreadsheet C#

I'm writing a application that reads Ia directory contents and writes that to a csv file. I'm trying to get a list of certain file extensions from and upload path which contains a csv file and write a list of the filtered extensions to a new csv file.
I cant figure out how to get the filtered csv file written.....
Here's my method.
StringBuilder CreateUserFileUploadList(SLDocument document, StringBuilder destroyWorksheet)
{
document.SelectWorksheet("User Folder");
var stats = document.GetWorksheetStatistics();
var rowcount = stats.EndRowIndex + 1;
List unwantedExtensions = cblExtensions.Items.Cast().Where(li => li.Selected).Select(li => li.Text).ToList();
if (!String.IsNullOrEmpty(tbOtherExtensions.Text))
{
unwantedExtensions.AddRange(tbOtherExtensions.Text.ToUpper().Split(new char[] { ',', ' ', '.' }, StringSplitOptions.RemoveEmptyEntries));
}
unwantedExtensions.AddRange("EXE,COM,BAT,JS,VBS,PIF,CMD,DLL,OCX,PWL".Split(new char[] { ',', ' ', '.' }, StringSplitOptions.RemoveEmptyEntries));
// new CSV file
var workSheet = new StringBuilder();
workSheet.AppendLine("FILEPATH,Client,Matter,LAST MODIFIED DATE,CREATED DATE,CREATED BY,LAST MODIFIED BY,FOLDER,DOCUMENT NAME,Author,Practice Area,Document Type,ACCESS,Keywords - Comments");
// loop through the directories
for (int i = 2; i 100 chars, or including TAB / \ : * ? " |
// Folder has folders>500 or has files>1000
//TODO: this loops through leaf folders; we need to check intermediate folders to ensure they don't have too many files or folders or a bad name
//Took out #"\",
bool invalidFolderName = new string[] { "/", ":", "*", "?", "" }.Any(s => directoryName.Contains(s));
if (invalidFolderName || directoryName.Length > 200 || files.Count() > 1000)
{
System.Diagnostics.Debug.WriteLine("INVALID folder: " + directoryName);
lblError.Text = lblError.Text + "\r\n" + "INVALID folder: " + directoryName;
//TODO: This should cause the WHOLE upload to fail
}
// build the target folder path
string folder;
string[] stringSeparators = new string[] { tbAuthor.Text };
var path = directoryName.Split(stringSeparators, StringSplitOptions.None);
folder = path.Last();
if (path.Count() > 1)
{
folder = ConfigurationManager.AppSettings["NetDocumentsFolderPath"].ToString() + tbAuthor.Text + #"\User Folder" + folder;
if (folder.Substring(folder.Length - 1, 1) == #"\")
{
folder = folder.Substring(0, folder.Length - 1);
}
}
// Get the files
foreach (var file in files)
{
// Remove unwanted extensions
if (!unwantedExtensions.Contains(file.Extension.Replace(".", "").ToUpper()))
{
var access = file.GetAccessControl();
string user = access.GetOwner(typeof(System.Security.Principal.NTAccount)).ToString();
//TODO: FWIW, fileName (on netdocs) does NOT need to match the name in the original location...
string fullName = file.FullName;
string fileName = file.Name;
// Wrap in quotes if there are any invalid characters
if (fullName.IndexOfAny(csvTokens) >= 0)
{
fullName = "\"" + fullName.Replace("\"", "\"\"") + "\"";
}
if (fileName.IndexOfAny(csvTokens) >= 0)
{
fileName = "\"" + fileName.Replace("\"", "\"\"") + "\"";
}
if (!document.GetCellValueAsString(i, 2).ToUpper().Contains("DESTROY"))
{
String practiceArea = GetPracticeAreaForClientMatter(document.GetCellValueAsString(i, 2), document.GetCellValueAsString(i, 3));
String documentType = ConfigurationManager.AppSettings["FileDocumentType"].ToString();
// Validate file
// Invalid file names (>200 chars, or TAB / \ : * ? " |
// Invalid file size (>200 MB)
bool invalidFileName = new string[] { "/", #"\", ":", "*", "?", "" }.Any(s => file.Name.Contains(s));
if (invalidFileName || file.Length > 200000000 || file.Name.Length > 200)
{
System.Diagnostics.Debug.WriteLine("INVALID file: " + file.Name);
lblError.Text = lblError.Text + "\r\n" + "INVALID file: " + file.Name;
//TODO: This should cause the WHOLE upload to fail
}
else
{
workSheet.AppendLine(
fullName + "," +
document.GetCellValueAsString(i, 2) + "," +
document.GetCellValueAsString(i, 3) + "," +
file.LastWriteTime + "," +
file.CreationTime + "," +
tbAuthor.Text + "," +
tbAuthor.Text + "," +
folder + "," +
fileName + "," +
tbAuthor.Text + "," +
practiceArea + "," +
documentType + "," +
practiceArea + "|V," +
"Imported from Departed Attorney on: " + DateTime.Now.ToString("G"));
}
}
else
{
destroyWorksheet.AppendLine(fullName);
}
}
}
}
bool invalidFileName = new string[] { "/", #"\", ":", "*", "?", "" }.Any(s => file.Name.Contains(s));
if (document.GetCellValueAsString(i, 2).ToUpper().Contains("DESTROY"))
{// Files in folders marked "destroy" are saved elsewhere
//destroyWorkSheet.Append(string.Format("{0}", "Directory" + fullName));
//destroyWorkSheet.Append(string.Format("{1}", "FileName" + fullName));
// destroyWorkSheet.AppendLine("Directory, FileName");
// destroyWorkSheet.Append(string.Format("{0},{1}", "Directory", "FileName") + fullName);
destroyWorksheet.AppendLine(fullName);
}
// Validate file for name (less than 200 chars, can't have TAB / \ : * ? " | ) and size ( less than 200 MB)
else if (invalidFileName || file.Length > 200000000 || file.Name.Length > 200)
{// This should cause the WHOLE upload to fail
System.Diagnostics.Debug.WriteLine("INVALID file: " + file.Name);
lblError.Text = lblError.Text + "\r\n" + "INVALID file: " + file.Name;
errorWorksheet.AppendLine("INVALID file: " + file.Name);
}
else if (unwantedExtensions.Contains(file.Extension.Replace(".", "").ToUpper()))
{// Files with unwanted extensions are filtered out
filterWorksheet.AppendLine(fullName);
}

Why is it generating newer files instead of moving the duplicates properly?

private void button4_Click(object sender, EventArgs e)
{
FileStream outputFileStream = new FileStream("log.txt", FileMode.Create, FileAccess.Write);
StreamWriter writer = new StreamWriter(outputFileStream);
// writing block
string originalPathFile = #"C:\Users\user\Downloads\CaptchaCollection\Small\";
string duplicatePath = #"C:\Users\user\Downloads\CaptchaCollection\Small\Duplicates\";
string movedOriginal = #"C:\Users\user\Downloads\CaptchaCollection\Small\Sorted\";
var files = Directory.GetFiles(originalPathFile)
.Select(nameWithExtension => Path.GetFileNameWithoutExtension(nameWithExtension))
.Where(name => { int number; return int.TryParse(name, out number); })
.Select(name => int.Parse(name))
.OrderBy(number => number).ToArray();
while (files.Length > 1)
{
string duplicateOfFolder = Directory.CreateDirectory(duplicatePath + files[0].ToString()).FullName;
for (int j = 1; j < files.Length; j++)
{
Bitmap im1 = new Bitmap(originalPathFile + files[0].ToString() + ".png");
Bitmap im2 = new Bitmap(originalPathFile + files[j].ToString() + ".png");
if (compare(im1, im2))
{
File.Move(originalPathFile + files[j].ToString() + ".png", duplicateOfFolder + files[j].ToString() + ".png");
writer.WriteLine(files[j].ToString() + ".png" + " is a duplicate of " + files[0].ToString() + ".png \n");
}
}
File.Move(originalPathFile + files[0].ToString() + ".png", movedOriginal + files[0].ToString() + ".png");
writer.WriteLine(files[0].ToString() + ".png " + "has had its duplicates removed.");
files = Directory.GetFiles(originalPathFile)
.Select(nameWithExtension => Path.GetFileNameWithoutExtension(nameWithExtension))
.Where(name => { int number; return int.TryParse(name, out number); })
.Select(name => int.Parse(name))
.OrderBy(number => number).ToArray();
}
writer.Close();
outputFileStream.Close();
}
So this button basically moves duplicate files of an image visually. I got this code from one of my previous questions I've asked. Now I want to use a new folder to place duplicates of a specific image.
For example:
1.png has 5 visual duplicates (65.png,87.png,100.png,103.png,156.png). I want to move all the duplicates to this directory instead of just placing it in the Duplicates directory: C:\Users\user\Downloads\CaptchaCollection\Small\Duplicates\1\
Now instead what's happening is that it apparently is renaming and regenerating some images. I can't really describe this in words because I can't really see what's going on. What's not happening is that those files are not being moved to the directory of a duplicated file organization.
Folders will create but instead it's not placing it in the proper folder.
If I understood your requirement correctly then I think issue is in following lines.
if (compare(im1, im2))
{
File.Move(originalPathFile + files[j].ToString() + ".png", duplicateOfFolder + files[j].ToString() + ".png");
writer.WriteLine(files[j].ToString() + ".png" + " is a duplicate of " + files[0].ToString() + ".png \n");
}
You are actually comparing first file with others but still copying the files in duplicate folder.
Replace following line
File.Move(originalPathFile + files[j].ToString() + ".png", duplicateOfFolder + files[j].ToString() + ".png");
with
String path = duplicateOfFolder;
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
File.Move(originalPathFile + files[j].ToString() + ".png", path + "\\" + files[j].ToString() + ".png");
This should work.

C# StreamWriter not writing to file

basicLog is a list of names and timestamps. I want to write them to a file. The two errors I'm getting are on the ';' on the StreamWriter line and on 'file.' on the second line.
The ';' error is: Possible mistaken empty statement
The error on file is: The name 'file' does not exist in the current context.
The file gets created just fine, but nothing gets written to it. I'm confused about file not existing in current context, because on the line prior it get's created. Thank you for any help.
foreach (BasicLog basicLog in emailAttach)
{
using (System.IO.StreamWriter file = new System.IO.StreamWriter(#"C:\\sorted.txt", true));
file.WriteLine(basicLog.LastName + " - " + basicLog.InOrOut + " - " + basicLog.EventTime + "\n");
}
Yes, you do have a mistaken empty statement.
remove the ';' and indent to show why:
foreach (BasicLog basicLog in emailAttach)
{
using (System.IO.StreamWriter file =
new System.IO.StreamWriter(#"C:\\sorted.txt", true)) //;
{
file.WriteLine(basicLog.LastName + " - " + basicLog.InOrOut + " - "
+ basicLog.EventTime + "\n");
}
}
The WriteLine() statement is (should be) under the control of the using(). The {} make that clearer.
This will work but note that it is very inefficient, you are reopening the file (for append) multiple times.
So it is better to invert the foreach/using:
using (System.IO.StreamWriter file =
new System.IO.StreamWriter(#"C:\\sorted.txt", true))
{
foreach (BasicLog basicLog in emailAttach)
{
file.WriteLine(basicLog.LastName + " - " + basicLog.InOrOut + " - "
+ basicLog.EventTime + "\n");
}
}
Ooops there is a semicolon at the end of the using line???
Perhaps your intention was:
using (System.IO.StreamWriter file = new System.IO.StreamWriter(#"C:\\sorted.txt", true))
{
foreach (BasicLog basicLog in emailAttach)
{
file.WriteLine(basicLog.LastName + " - " + basicLog.InOrOut + " - " + basicLog.EventTime + "\n");
}
}
Curious, the same thing happened to me this morning :-)
You are disposing the StreamWriter before writing to the file. Refactor to this:
using (System.IO.StreamWriter file = new System.IO.StreamWriter(#"C:\\sorted.txt", true))
{
foreach (BasicLog basicLog in emailAttach)
{
file.WriteLine(basicLog.LastName + " - " + basicLog.InOrOut + " - " + basicLog.EventTime + "\n");
}
}
Your file instance will get Disposed right after this line (Since you're using using):
using (System.IO.StreamWriter file = new System.IO.StreamWriter(#"C:\\sorted.txt", true));
Change it to
System.IO.StreamWriter file = new System.IO.StreamWriter(#"C:\\sorted.txt", true);
Or the full code,
System.IO.StreamWriter file;
foreach (BasicLog basicLog in emailAttach)
{
file = new System.IO.StreamWriter(#"C:\\sorted.txt", true);
file.WriteLine(basicLog.LastName + " - " + basicLog.InOrOut + " - " + basicLog.EventTime + "\n");
}
Or make a correct use of using
foreach (BasicLog basicLog in emailAttach)
{
using(System.IO.StreamWriter file = new System.IO.StreamWriter(#"C:\\sorted.txt", true))
{
file.WriteLine(basicLog.LastName + " - " + basicLog.InOrOut + " - " + basicLog.EventTime + "\n");
}
}

Categories