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");
}
}
Related
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); });
}
}
}
I have this code:
using (var sw = new StreamWriter(path + kat + "/" + namec, false, Encoding.UTF8))
{
sw.WriteLine(namex + "," + address + "," + web + "," + email + "," + phone + "," + linksx + "," + transport);
}
How I can append text and include Encoding.UTF8 ?
I tried this:
using (StreamWriter sw = File.AppendText(path + kat + "/" + namec, false, Encoding.UTF8))
But i got this:
Severity Code Description Project File Line Suppression State
Error CS1501 No overload for method 'AppendText' takes 3
arguments visitdenmark C:\Users\???\Documents\Visual Studio
2015\Projects\visitdenmark\visitdenmark\Form1.cs 193 Active
Actually the error message is correct. Claiming that AppendText does not take 3 arguments.
But in my optinion there is no need to leave your first approach with the StreamWriter aside. But in order to append the text you should change the second parameter to true
using (var sw = new StreamWriter(path + kat + "/" + namec, true, Encoding.UTF8))
{
sw.WriteLine(namex + "," + address + "," + web + "," + email + "," + phone + "," + linksx + "," + transport);
}
Is there a way to add a pause (preferably 1 second) in Amazon Alexa without using SSML? Perhaps there is a trick I can do with the Outputspeech.Text and I just don't know it.
Below, I am saying "Here are works of art by {artist name}" but the name and the start of the works of art become mixed together - in spite of the period - so I end up with things like "Here are the works of art by Pablo Picasso Harlequin..."
I am using C# and my own https endpoint, not AWS Lambda.
Any suggestions? Otherwise I will add it as SSML. Thanks.
var output = new StringBuilder();
var outputCard = new StringBuilder();
string m_location;
string m_current_location;
string m_artist = dt_artist.Rows[0]["DisplayName"].ToString();
output.Append("here are works of art for " + m_artist + ". ");
outputCard.Append("Here are works of art for " + m_artist + ".\n\n");
foreach (DataRow dr in dt_artist_objs.Rows)
{
m_current_location = dr["CurrentLocation"].ToString();
if (m_current_location == " ")
{
m_location = "The location is not available.";
}
else
{
m_location = "It is located on the " + m_current_location;
}
output.Append(dr["Title"].ToString() + " is a " + dr["Classification"].ToString() + ". The medium is " + dr["Medium"].ToString() + ". " + m_location);
outputCard.Append(dr["Title"].ToString() + ", " + dr["Dated"].ToString() + " is a " + dr["Classification"].ToString() + ". The medium is " + dr["Medium"].ToString() + ". " + dr["Creditline"].ToString() + ". " + m_location + ".\n"); // It is located on the " + dr["CurrentLocation"].ToString());
}
sql_conn_data.Close();
response.Response.OutputSpeech.Text = output.ToString();
response.Response.Card.Title = "Art";
response.Response.Card.Type = "Standard";
response.Response.Card.Text = outputCard.ToString();
response.Response.ShouldEndSession = true;
return response;
UPDATE
OK. Ended up going the SSML route which looks like this:
var output = new StringBuilder();
var outputCard = new StringBuilder();
string m_location;
string m_current_location;
string m_location_card;
string m_artist = dt_artist.Rows[0]["DisplayName"].ToString();
output.Append("<speak>");
output.Append("here are works of art for " + m_artist + ". <break time='1s'/> ");
outputCard.Append("Here are works of art for " + m_artist + ".\n\n");
foreach (DataRow dr in dt_artist_objs.Rows)
{
m_current_location = dr["CurrentLocation"].ToString();
if (m_current_location == " ")
{
m_location = "The location is not available. <break time='1s' />";
m_location_card = "The location is not available. ";
}
else
{
m_location = "It is located on the " + m_current_location + "<break time = '1s' />";
m_location_card = "It is located on the " + m_current_location;
}
output.Append(dr["Title"].ToString() + " is a " + dr["Classification"].ToString() + ". The medium is " + dr["Medium"].ToString() + ". " + m_location);
outputCard.Append(dr["Title"].ToString() + ", " + dr["Dated"].ToString() + " is a " + dr["Classification"].ToString() + ". The medium is " + dr["Medium"].ToString() + ". " + dr["Creditline"].ToString() + ". " + m_location_card + ". \n");
}
output.Append("</speak>");
sql_conn_data.Close();
response.Response.OutputSpeech.Ssml = output.ToString();
response.Response.OutputSpeech.Type = "SSML";
response.Response.Card.Title = "Art";
response.Response.Card.Type = "Standard";
response.Response.Card.Text = outputCard.ToString();
response.Response.ShouldEndSession = true;
return response;
}
There is not a way to introduce a pause in Alexa without SSML. You will need to build the ssml string and return it back to Alexa using the pause, or the cadence strings.
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);
}
}
}
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.