How do i use net user inside a C# console program? [closed] - c#

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I can't seem to get it to work, the only thing that happens is a CMD prompt pops up saying how to use the net function, if you could help me please, i would be grateful.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
using System.IO;
namespace Enable_Elevated_Admin
{
class Program
{
static void Main(string[] args)
{
Console.Title = "Enable Admin";
Process enable_admin = new Process();
Process disable_admin = new Process();
enable_admin.StartInfo.Arguments = "user " + "administrator" + "/active:yes";
enable_admin.StartInfo.FileName = #"C:\Windows\System32\net";
disable_admin.StartInfo.Arguments = "user " + "administrator" + "/active:no";
disable_admin.StartInfo.FileName = #"C:\Windows\System32\net";
ConsoleKeyInfo i;
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine("Welcome to ClassyJakey's C# project for enabling the elevated admin easily.");
Console.WriteLine("Options :");
Console.WriteLine("1) Enable elevated admin");
Console.WriteLine("2) Disable elevated admin");
i = Console.ReadKey();
if (i.KeyChar.ToString() == "1")
{
Console.WriteLine("Enabling admin, please wait!");
enable_admin.Start();
Console.WriteLine("Enabled!");
Console.ReadKey();
Console.WriteLine("Creating log...");
StreamWriter writer = new StreamWriter("c:\\log.txt");
writer.WriteLine(System.DateTime.Today);
writer.WriteLine("Enable Admin Log - By ClassyJakey");
writer.WriteLine("Enabling admin was successful!");
writer.WriteLine("If you have errors, please contact classyjakey.");
writer.Close();
}
if (i.KeyChar.ToString() == "2")
{
Console.WriteLine("Disabling admin, please wait!");
disable_admin.Start();
Console.WriteLine("Disabled!");
Console.ReadKey();
StreamWriter writer2 = new StreamWriter("c:\\log2.txt");
writer2.WriteLine(System.DateTime.Today);
writer2.WriteLine("Enable Admin Log - By ClassyJakey");
writer2.WriteLine("Disabling! admin was successful!");
writer2.WriteLine("If you have errors, please contact classyjakey.");
writer2.Close();
}
else
{
Console.WriteLine("You thought you would find a easter egg by not putting 1 or 2?");
Console.WriteLine("Well, your right.");
Console.WriteLine("+ o + o ");
Console.WriteLine(" + o + +");
Console.WriteLine("o + ");
Console.WriteLine(" o + + + ");
Console.WriteLine("+ o o + o");
Console.WriteLine("-_-_-_-_-_-_-_,------, o ");
Console.WriteLine(#"_-_-_-_-_-_-_-| /\_/\ meow ");
Console.WriteLine("-_-_-_-_-_-_-_|__( ^ w^) + +");
Console.WriteLine(#"_-_-_-_-_-_-_- "" "" ");
Console.WriteLine("+ o o + o ");
Console.WriteLine(" + + ");
Console.WriteLine("o o o o +");
Console.WriteLine(" o + ");
Console.WriteLine("+ + o o + ");
StreamWriter writer3 = new StreamWriter("c:\\log3.txt");
writer3.WriteLine(System.DateTime.Today);
writer3.WriteLine("+ o + o ");
writer3.WriteLine(" + o + +");
writer3.WriteLine("o + ");
writer3.WriteLine(" o + + + ");
writer3.WriteLine("+ o o + o");
writer3.WriteLine("-_-_-_-_-_-_-_,------, o ");
writer3.WriteLine(#"_-_-_-_-_-_-_-| /\_/\ meow ");
writer3.WriteLine("-_-_-_-_-_-_-_|__( ^ w^) + +");
writer3.WriteLine(#"_-_-_-_-_-_-_- "" "" ");
writer3.WriteLine("+ o o + o ");
writer3.WriteLine(" + + ");
writer3.WriteLine("o o o o +");
writer3.WriteLine(" o + ");
writer3.WriteLine("+ + o o + ");
writer3.Close();
Console.ReadKey();
}
}
}
}

Probably because you're missing a space to separate the arguments:
enable_admin.StartInfo.Arguments = "user " + "administrator " + "/active:yes";
^----
enable_admin.StartInfo.FileName = #"C:\Windows\System32\net";
disable_admin.StartInfo.Arguments = "user " + "administrator " + "/active:no";
^----
disable_admin.StartInfo.FileName = #"C:\Windows\System32\net";

Related

Finding an Employee without using so many Conditional Statements using Structs

I have written this code for my school project program (it's still incomplete) but it does the job for the most part. The thing is, we have to use structs to make a program of pre-defined employees and then we have to make it so that we can use any attribute (Name, Employee ID, Blood group, Age etc.) to search through all of the employees.
I have found a way using conditional statements (which as of right now, works for name and employee ID). I have realized that the code is too long and there might be another way to search through the program. I also want to make it show all male/female employees when we use Gender as the searching attribute.
Here is my code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Terminals
{
class Program
{
struct Employee
{
public string Name;
public int EmployeeID;
public string BloodGroup;
public int Salary;
public int Age;
public string Gender;
}
static void Main(string[] args)
{
Employee employee1;
Employee employee2;
Employee employee3;
Employee employee4;
Employee employee5;
Employee employee6;
employee1.Name = "James";
employee1.EmployeeID = int.Parse("10");
employee1.BloodGroup = "B +ive";
employee1.Salary = int.Parse("500000");
employee1.Age = int.Parse("26");
employee1.Gender = "Male";
employee2.Name = "Ali Khan";
employee2.EmployeeID = int.Parse("20");
employee2.BloodGroup = "O +ive";
employee2.Salary = int.Parse("250000");
employee2.Age = int.Parse("22");
employee2.Gender = "Male";
employee3.Name = "Jessica Hills";
employee3.EmployeeID = int.Parse("30");
employee3.BloodGroup = "A -ive";
employee3.Salary = int.Parse("400000");
employee3.Age = int.Parse("25");
employee3.Gender = "Female";
employee4.Name = "William";
employee4.EmployeeID = int.Parse("40");
employee4.BloodGroup = "O -ive";
employee4.Salary = int.Parse("700000");
employee4.Age = int.Parse("29");
employee4.Gender = "Male";
employee5.Name = "Lizzy";
employee5.EmployeeID = int.Parse("50");
employee5.BloodGroup = "AB +ive";
employee5.Salary = int.Parse("70000");
employee5.Age = int.Parse("19");
employee5.Gender = "Female";
employee6.Name = "Kyle";
employee6.EmployeeID = int.Parse("60");
employee6.BloodGroup = "AB -ive";
employee6.Salary = int.Parse("600000");
employee6.Age = int.Parse("21");
employee6.Gender = "Male";
Console.WriteLine("Please enter the number of the term you would like to search with (1-6)?");
Console.WriteLine("1. Name");
Console.WriteLine("2. Employee ID");
Console.WriteLine("3. Blood Group");
Console.WriteLine("4. Salary");
Console.WriteLine("5. Age");
Console.WriteLine("6. Gender");
Console.WriteLine("Please enter the number (1-6): ");
int searchterm = int.Parse(Console.ReadLine());
if (searchterm == 1)
{
Console.WriteLine("Please enter the name of the employee: ");
string name = Console.ReadLine();
if (name == employee1.Name)
{
Console.Write("Name: " + employee1.Name);
Console.WriteLine("Employee ID: " + employee1.EmployeeID);
Console.WriteLine("Blood Group: " + employee1.BloodGroup);
Console.WriteLine("Salary: " + employee1.Salary);
Console.WriteLine("Age: " + employee1.Age);
Console.WriteLine("Gender: " + employee1.Gender);
Console.ReadKey();
}
else if (name == employee2.Name)
{
Console.Write("Name: " + employee2.Name);
Console.WriteLine("Employee ID: " + employee2.EmployeeID);
Console.WriteLine("Blood Group: " + employee2.BloodGroup);
Console.WriteLine("Salary: " + employee2.Salary);
Console.WriteLine("Age: " + employee2.Age);
Console.WriteLine("Gender: " + employee2.Gender);
Console.ReadKey();
}
else if (name == employee3.Name)
{
Console.Write("Name: " + employee3.Name);
Console.WriteLine("Employee ID: " + employee3.EmployeeID);
Console.WriteLine("Blood Group: " + employee3.BloodGroup);
Console.WriteLine("Salary: " + employee3.Salary);
Console.WriteLine("Age: " + employee3.Age);
Console.WriteLine("Gender: " + employee3.Gender);
Console.ReadKey();
}
else if (name == employee4.Name)
{
Console.Write("Name: " + employee4.Name);
Console.WriteLine("Employee ID: " + employee4.EmployeeID);
Console.WriteLine("Blood Group: " + employee4.BloodGroup);
Console.WriteLine("Salary: " + employee4.Salary);
Console.WriteLine("Age: " + employee4.Age);
Console.WriteLine("Gender: " + employee4.Gender);
Console.ReadKey();
}
else if (name == employee5.Name)
{
Console.Write("Name: " + employee5.Name);
Console.WriteLine("Employee ID: " + employee5.EmployeeID);
Console.WriteLine("Blood Group: " + employee5.BloodGroup);
Console.WriteLine("Salary: " + employee5.Salary);
Console.WriteLine("Age: " + employee5.Age);
Console.WriteLine("Gender: " + employee5.Gender);
Console.ReadKey();
}
else if (name == employee6.Name)
{
Console.Write("Name: " + employee1.Name);
Console.WriteLine("Employee ID: " + employee6.EmployeeID);
Console.WriteLine("Blood Group: " + employee6.BloodGroup);
Console.WriteLine("Salary: " + employee6.Salary);
Console.WriteLine("Age: " + employee6.Age);
Console.WriteLine("Gender: " + employee6.Gender);
Console.ReadKey();
}
else
{
Console.WriteLine("Please try again.");
return;
}
}
if (searchterm == 2)
{
Console.WriteLine("Please enter the employee ID of the employee");
int employeeid = int.Parse(Console.ReadLine());
if (employeeid == employee1.EmployeeID)
{
Console.Write("Name: " + employee1.Name);
Console.WriteLine("Employee ID: " + employee1.EmployeeID);
Console.WriteLine("Blood Group: " + employee1.BloodGroup);
Console.WriteLine("Salary: " + employee1.Salary);
Console.WriteLine("Age: " + employee1.Age);
Console.WriteLine("Gender: " + employee1.Gender);
Console.ReadKey();
}
else if (employeeid == employee2.EmployeeID)
{
Console.Write("Name: " + employee2.Name);
Console.WriteLine("Employee ID: " + employee2.EmployeeID);
Console.WriteLine("Blood Group: " + employee2.BloodGroup);
Console.WriteLine("Salary: " + employee2.Salary);
Console.WriteLine("Age: " + employee2.Age);
Console.WriteLine("Gender: " + employee2.Gender);
Console.ReadKey();
}
else if (employeeid == employee3.EmployeeID)
{
Console.Write("Name: " + employee3.Name);
Console.WriteLine("Employee ID: " + employee3.EmployeeID);
Console.WriteLine("Blood Group: " + employee3.BloodGroup);
Console.WriteLine("Salary: " + employee3.Salary);
Console.WriteLine("Age: " + employee3.Age);
Console.WriteLine("Gender: " + employee3.Gender);
Console.ReadKey();
}
else if (employeeid == employee4.EmployeeID)
{
Console.Write("Name: " + employee4.Name);
Console.WriteLine("Employee ID: " + employee4.EmployeeID);
Console.WriteLine("Blood Group: " + employee4.BloodGroup);
Console.WriteLine("Salary: " + employee4.Salary);
Console.WriteLine("Age: " + employee4.Age);
Console.WriteLine("Gender: " + employee4.Gender);
Console.ReadKey();
}
else if (employeeid == employee5.EmployeeID)
{
Console.Write("Name: " + employee5.Name);
Console.WriteLine("Employee ID: " + employee5.EmployeeID);
Console.WriteLine("Blood Group: " + employee5.BloodGroup);
Console.WriteLine("Salary: " + employee5.Salary);
Console.WriteLine("Age: " + employee5.Age);
Console.WriteLine("Gender: " + employee5.Gender);
Console.ReadKey();
}
else if (employeeid == employee6.EmployeeID)
{
Console.Write("Name: " + employee6.Name +" ");
Console.WriteLine("Employee ID: " + employee6.EmployeeID);
Console.WriteLine("Blood Group: " + employee6.BloodGroup);
Console.WriteLine("Salary: " + employee6.Salary);
Console.WriteLine("Age: " + employee6.Age);
Console.WriteLine("Gender: " + employee6.Gender);
Console.ReadKey();
}
else
{
Console.WriteLine("Please try again.");
Console.ReadKey();
return;
}
}
}
}
}
As others said, LINQ will be your friend here, and using a collection, like a List<Employee> also helps tremendously. You can eliminate the else if logic and shorten the code up by a good amount.
For the Employee emp = employeeList.Find(employee => employee.Name == name); line, you would need to change the predicate to Find by the correct struct member depending on the user input. If it can't find the Employee out of the list, the else logic will report so (this too would also need to be specific to each search condition). I also added a private method to seed the list of employees. A simple method to contain all the console output lines will also shorten this up even more - simply supply the found Employee to it.
The only issue with this is if two or more employees have the same value for one of their members. It looks like none of your seeded employees share anything in common except Gender, in which case you would need to filter on an additional attribute to narrow it down to one employee, or output all the found employees by the search criteria. .Find will return the first Employee that matches the criteria, so that won't work (or at least, it would only output the first found Employee!) You could change this code to use .FindAll instead, and then pass a new List<Employee> to the private methods, and loop over all the employees in the list, outputting each of their information. Overloading the ValidateEmployee method I wrote to take in a List<Employee> should do the trick. You could make all your conditions perform a .FindAll and delete the ValidateEmployee method that takes in a single Employee, up to you!
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Terminals
{
class Program
{
struct Employee
{
public string Name;
public int EmployeeID;
public string BloodGroup;
public int Salary;
public int Age;
public string Gender;
}
static void Main(string[] args)
{
List<Employee> employeeList = SeedEmployees();
Console.WriteLine("Please enter the number of the term you would like to search with (1-6):");
Console.WriteLine("1. Name");
Console.WriteLine("2. Employee ID");
Console.WriteLine("3. Blood Group");
Console.WriteLine("4. Salary");
Console.WriteLine("5. Age");
Console.WriteLine("6. Gender");
Console.WriteLine("Please enter the number (1-6): ");
int searchterm = int.Parse(Console.ReadLine());
if (searchterm == 1)
{
Console.WriteLine("Please enter the name of the employee: ");
string name = Console.ReadLine();
Employee emp = employeeList.Find(employee => employee.Name == name);
ValidateEmployee(emp);
}
else if (searchterm == 6)
{
Console.WriteLine("Please enter the gender of the employee: ");
string gender = Console.ReadLine();
List<Employee> emps = employeeList.FindAll(employee => employee.Gender == gender);
ValidateEmployee(emps);
}
//the rest of your "if" conditions for search terms...
else
{
Console.WriteLine("Please try again.");
Console.ReadKey();
return;
}
Console.WriteLine("Done. Press any key to exit...");
Console.ReadLine();
}
private static void ValidateEmployee(Employee emp)
{
if (emp.Equals(default(Employee)))
{
//employee not found
Console.WriteLine($"Employee not found by supplied input. Please try again.");
Console.ReadLine();
return;
}
else
{
//output the emplyee info
OutputEmployeeInfo(emp);
}
}
private static void ValidateEmployee(List<Employee> emps)
{
foreach (Employee emp in emps)
{
if (emp.Equals(default(Employee)))
{
//employee not found
Console.WriteLine($"Employee not found by supplied input.");
}
else
{
//output the emplyee info
OutputEmployeeInfo(emp);
}
}
}
private static void OutputEmployeeInfo(Employee employee)
{
Console.Write("Name: " + employee.Name);
Console.WriteLine("Employee ID: " + employee.EmployeeID);
Console.WriteLine("Blood Group: " + employee.BloodGroup);
Console.WriteLine("Salary: " + employee.Salary);
Console.WriteLine("Age: " + employee.Age);
Console.WriteLine("Gender: " + employee.Gender);
Console.ReadKey();
}
private static List<Employee> SeedEmployees()
{
Employee employee1;
Employee employee2;
Employee employee3;
Employee employee4;
Employee employee5;
Employee employee6;
employee1.Name = "James";
employee1.EmployeeID = int.Parse("10");
employee1.BloodGroup = "B +ive";
employee1.Salary = int.Parse("500000");
employee1.Age = int.Parse("26");
employee1.Gender = "Male";
employee2.Name = "Ali Khan";
employee2.EmployeeID = int.Parse("20");
employee2.BloodGroup = "O +ive";
employee2.Salary = int.Parse("250000");
employee2.Age = int.Parse("22");
employee2.Gender = "Male";
employee3.Name = "Jessica Hills";
employee3.EmployeeID = int.Parse("30");
employee3.BloodGroup = "A -ive";
employee3.Salary = int.Parse("400000");
employee3.Age = int.Parse("25");
employee3.Gender = "Female";
employee4.Name = "William";
employee4.EmployeeID = int.Parse("40");
employee4.BloodGroup = "O -ive";
employee4.Salary = int.Parse("700000");
employee4.Age = int.Parse("29");
employee4.Gender = "Male";
employee5.Name = "Lizzy";
employee5.EmployeeID = int.Parse("50");
employee5.BloodGroup = "AB +ive";
employee5.Salary = int.Parse("70000");
employee5.Age = int.Parse("19");
employee5.Gender = "Female";
employee6.Name = "Kyle";
employee6.EmployeeID = int.Parse("60");
employee6.BloodGroup = "AB -ive";
employee6.Salary = int.Parse("600000");
employee6.Age = int.Parse("21");
employee6.Gender = "Male";
return new List<Employee>
{
employee1,
employee2,
employee3,
employee4,
employee5,
employee6
};
}
}
}

Iterating through with PSObject in C#

I am trying to get the values of the properties of an Active Directory instance.
But it keeps giving me null exceptions
The code I am using is as follows.
var xs = PowerShell.Create()
.AddScript("Get-ADComputer -Identity COM-PC-003$ -Properties * | select operatingsystem, accountexpires")
.AddCommand("out-string");
Collection<PSObject> results = xs.Invoke();
//Console.WriteLine(xs);
foreach (var str in results)
{
Console.WriteLine(str.Members["operatingsystem"].Value.ToString());
Console.ReadLine();
//System.Diagnostics.Debug.WriteLine(str.Properties["operatingsystem"].Value);
}
How can I fix this problem?
You can try to do this:
while (true) {
Console.WriteLine("Enter Hostname");
var hn = Console.ReadLine();
var xs = PowerShell.Create().AddScript(
"$comp = Get-ADComputer -Identity " + hn +
" -Properties *" + Environment.NewLine +
"$obj = New-Object -TypeName psobject" +
" -Property #{Host=$comp.operatingsystem;accountexpires = $comp.accountexpires}" +
Environment.NewLine +
"$obj1 = $obj | select -ExpandProperty Host ; $obj2 = $obj | select -ExpandProperty accountexpires ; $out = $obj1 + ' ; ' + $obj2 ; $out").AddCommand("out-string");
Collection<PSObject> results = xs.Invoke();
//Console.WriteLine(xs);
foreach (var str in results)
{
Console.WriteLine("You want to see only OS vers? If its true - enter H, also enter E for see accountexpires or A for see all info");
ConsoleKeyInfo c = Console.ReadKey();
if (c.KeyChar == 'H')
{
Console.WriteLine(str.ToString().Split(';')[0]);
Console.ReadLine();
}
if (c.KeyChar == 'E')
{
Console.WriteLine(str.ToString().Split(';')[1]);
Console.ReadLine();
}
if (c.KeyChar == 'A')
{
Console.WriteLine(str.ToString());
Console.ReadLine();
}
}
}

Add pause to Alexa without using SSML

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.

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);
}
}
}

How to detect/find the end of while loop?

I'm performing a "while" loop in C#, this is going through some records being pulled from a DB. What's the best way to detect/find the last record on the loop? Is this possible?
Here is my code:
while (sdr.Read())
{
//Pull each line from DB
the_title = sdr["the_title"].ToString();
the_cats = sdr["the_category"].ToString();
the_tags = sdr["the_tags"].ToString();
the_date = sdr["the_date"].ToString();
//Start file creation
writer.WriteLine("[");
writer.WriteLine("\"" + the_title + "\", ");
writer.WriteLine("\"" + the_cats + "\", ");
writer.WriteLine("\"" + the_tags + "\", ");
writer.WriteLine("\"" + the_date + "\", ");
writer.WriteLine("\"<i class=\\\"icon-pencil\\\"></i>\"");
writer.WriteLine("],");
}
writer.WriteLine("]");
writer.WriteLine("}");
writer.Close();
The problem I'm having is with the last line of code "writer.WriteLine("],");" I need to remove that comma on the last record being pulled from the DB.
thank you
Do it the other way around:
bool is_first = true;
while (sdr.Read()) {
if (is_first) {
is_first = false;
} else {
writer.Write(",");
}
// Do your other writes here
}
I would suggest you to just remove the last character. It is the most efficient solution within a loop.
StringBuilder sb = new StringBuilder();
while (sdr.Read())
{
sb.Append("Value");
....
}
if(sb.Length > 0)
{
sb.Remove(sb.Length - 1, 1)
}
var result = sb.ToString();
Another approach that should work:
List<String> bufferList = new List<String>();
while (sdr.Read())
{
//Pull each line from DB
the_title = sdr["the_title"].ToString();
the_cats = sdr["the_category"].ToString();
the_tags = sdr["the_tags"].ToString();
the_date = sdr["the_date"].ToString();
StringBuilder tempSb = new StringBuilder();
tempSb.AppendLine();
//Start file creation
tempSb.AppendLine("[");
tempSb.AppendLine("\"" + the_title + "\", ");
tempSb.AppendLine("\"" + the_cats + "\", ");
tempSb.AppendLine("\"" + the_tags + "\", ");
tempSb.AppendLine("\"" + the_date + "\", ");
tempSb.AppendLine("\"<i class=\\\"icon-pencil\\\"></i>\"");
tempSb.AppendLine(("]");
bufferList.Add(tempSb.ToString());
}
String.Join(",", bufferList);
Yet another approach
if(sdr.Read()) {
while (true) {
...
writer.WriteLine("[");
...
if (!sdr.Read()) {
writer.WriteLine("]");
break;
}
writer.WriteLine("],");
}
}
You can't know the last (up until you've reached/passed it), but you can know the first. You can modify your code as:
bool isFirst = true;
while (sdr.Read())
{
if (isFirst) isFirst = false;
else writer.WriteLine(",");
//Pull each line from DB
the_title = sdr["the_title"].ToString();
the_cats = sdr["the_category"].ToString();
the_tags = sdr["the_tags"].ToString();
the_date = sdr["the_date"].ToString();
//Start file creation
writer.WriteLine("[");
writer.WriteLine("\"" + the_title + "\", ");
writer.WriteLine("\"" + the_cats + "\", ");
writer.WriteLine("\"" + the_tags + "\", ");
writer.WriteLine("\"" + the_date + "\", ");
writer.WriteLine("\"<i class=\\\"icon-pencil\\\"></i>\"");
writer.Write("]");
}
writer.WriteLine();
Else, to avoid the check in every instance of the loop, you could use:
var sb = new StringBuilder();
while (sdr.Read())
{
//Pull each line from DB
the_title = sdr["the_title"].ToString();
the_cats = sdr["the_category"].ToString();
the_tags = sdr["the_tags"].ToString();
the_date = sdr["the_date"].ToString();
//Start file creation
sb.AppendLine("[");
sb.AppendLine("\"" + the_title + "\", ");
sb.AppendLine("\"" + the_cats + "\", ");
sb.AppendLine("\"" + the_tags + "\", ");
sb.AppendLine("\"" + the_date + "\", ");
sb.AppendLine("\"<i class=\\\"icon-pencil\\\"></i>\"");
sb.AppendLine("],");
}
if (sb.Length > 0)
{
// Write result, sans characters for last newline (Environment.NewLine) and comma.
writer.WriteLine(sb.ToString(0, sb.Length - (Environment.NewLine.Length + 1));
}
EDIT: Made clipping length dynamic by using Environment.NewLine.Length.

Categories