I want to make a program to read the total number of drives in system and make list view to show its information that is, counting the number of folders and files individually in each drive present and there is some error due to which I am not able to solve that problem. Please help me in finding the error in the same.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using SystemInformation;
using SystemInformation.Properties;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using MySql.Data.MySqlClient;
using System.Diagnostics;
using System.IO;
namespace SystemInformation
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
try
{
DriveInfo[] drives = DriveInfo.GetDrives();
foreach (DriveInfo drive in drives)
{
ListViewItem item = new ListViewItem();
var k = Console.WriteLine(drive.Name);
item.SubItems.Add(k);
foreach (string path in Directory.EnumerateFiles(drive.Name))
{
Console.WriteLine(path);
lstInfo.Items.Add(item);
}
}
}
catch (MySqlException ex)
{
Trace.WriteLine(ex.Message);
}
catch (Exception ex)
{
Trace.WriteLine(ex.Message);
}
}
public string k { get; set; }
}
}
First of all, the method Console.WriteLine() is void and you can't get an output from it.
You can't do multiple levels using listview. You will need to use TreeView instead.
The following code will give you the file structure on you computer:
private void Form1_Load(object sender, EventArgs e)
{
DriveInfo[] drives = DriveInfo.GetDrives();
foreach (DriveInfo drive in drives)
{
var item = TV_Items.Nodes.Add(drive.Name);
AddDirectories(item, drive.Name);
}
}
private void AddDirectories(TreeNode parent, string path)
{
var directories = Directory.GetDirectories(path);
foreach (var directory in directories)
{
try
{
var subItem = parent.Nodes.Add(Path.GetDirectoryName(directory));
foreach (var file in Directory.GetFiles(directory))
{
subItem.Nodes.Add(Path.GetFileNameWithoutExtension(file));
}
AddDirectories(subItem, directory);
}
catch (Exception ex)
{
Debug.WriteLine(ex.Message);
}
}
}
I didn't understand what do you want to count exactly. Is it the number of folders and files in each folder or just in each drive?
Related
What i'm trying to do here is to loop a few websites and have the page displayed in the CefSharp browser.
Code:
using CefSharp;
using CefSharp.WinForms;
using System;
using System.IO;
using System.Threading;
using System.Windows.Forms;
namespace rankjester
{
public partial class FormBrowser : Form
{
public ChromiumWebBrowser browser;
private readonly FormMain _formMain;
readonly string[] listOfSites;
public FormBrowser(string[] sitesList, FormMain formMain)
{
InitializeComponent();
_formMain = formMain;
//InitChromeBrowser(sitesList);
listOfSites = sitesList;
}
public string InitChromeBrowser(string site)
{
var complete = string.Empty;
try
{
// Init CEF.
CefSettings settings = new CefSettings
{
CachePath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), #"cache\")
};
Cef.Initialize(settings);
browserMain.Text = "BROWSER - [ " + #"https://www." + site + " ] ";
browser = new ChromiumWebBrowser(#"https://www." + site);
panelBrowser1.Controls.Add(browser);
browser.Dock = DockStyle.Fill;
}
catch (Exception ex)
{
Helpers.DebugLogging($"[{DateTime.Now}]-[{ex}]");
}
return complete;
}
private void FormBrowser_FormClosing(object sender, FormClosingEventArgs e)
{
browser.Dispose();
Cef.Shutdown();
}
private void FormBrowser_Load(object sender, EventArgs e)
{
try
{
foreach (var site in listOfSites) {
InitChromeBrowser(site);
}
}
catch (Exception ex)
{
Helpers.DebugLogging($"[{DateTime.Now}]-[{ex}]");
}
}
}
}
The code is pretty simple enough, i'm passing through an array of the sites to display, and then loop them, the problem is only the first checked site is displayed, the foreach does not move to the next site (at least not in the browser) when i check via a MsgBox all sites are passed through fine. am i missing something simple? any help is appreciated.
This is a pretty simple program. It IS a homework project. The program should start, read a .txt file, populate the name list and when you click on the name, the phone number is displayed. I have it coded, no errors, no warnings. It will not read the .txt file and I can't figure out why. I've been scouring my book, youtube, even here, but can't pin it down. Any help would be appreciated. Here is my current 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.IO;
namespace Phonebook
{
struct PhoneBookEntry
{
public string name;
public string phone;
}
public partial class Form1 : Form
{
// FIeld to hold a list of PhoneBookEntry objects.
private List<PhoneBookEntry> phoneList = new List<PhoneBookEntry>();
public Form1()
{
InitializeComponent();
}
// The ReadFile method reads the contents of the
//PhoneList.txt file and tores it as PhoneBokeEntry
// objects in the phoneList.
private void ReadFile()
{
try
{
StreamReader inputFile; // To read the file
string line; // To hold a line from the file
// Create an instance of the PhoneBookEntry structure.
PhoneBookEntry entry = new PhoneBookEntry();
// Create a delimiter array.
char[] delim = { ',' };
// Open the PhoneList file.
inputFile = File.OpenText("PhoneList.txt");
// Read the lines from the file.
while (!inputFile.EndOfStream)
{
// Read a line from the file.
line = inputFile.ReadLine();
// Tokenize the line
string[] tokens = line.Split(delim);
// Store the tokens in the entry object.
entry.name = tokens[0];
entry.phone = tokens[1];
// Add the entry object to the List.
phoneList.Add(entry);
}
}
catch (Exception ex)
{
// Display an error message.
MessageBox.Show(ex.Message);
}
}
// The DisplayNames method displays the list of names
// in the namesListBox conrol.
private void DisplayNames()
{
foreach (PhoneBookEntry entry in phoneList)
{
nameListBox.Items.Add(entry.name);
}
}
private void Form1_Load(object sender, EventArgs e)
{
// Read the PhoneList.txt file.
ReadFile();
// DIsplay the names.
DisplayNames();
}
private void nameListBox_SelectedIndexChanged(object sender, EventArgs e)
{
// Get the index of the selected item.
int index = nameListBox.SelectedIndex;
// Display the corresponding phone number.
phoneLabel.Text = phoneList[index].phone;
}
private void exitButton_Click(object sender, EventArgs e)
{
// close the form.
this.Close();
}
private void Form1_Load_1(object sender, EventArgs e)
{
}
}
}
so my issue is that, I can´t make my DataGridView read information from a text file already created, don´t know what to do really, I am kinda new to C#, so I hope you can help me :D
Here is my code to save the values from my grid:
private void buttonGuardar_Click(object sender, EventArgs e)
{
string[] conteudo = new string[dataGridView1.RowCount * dataGridView1.ColumnCount];
int cont = 0;
foreach (DataGridViewRow row in dataGridView1.Rows)
{
foreach (DataGridViewCell cell in row.Cells)
{
conteudo[cont++] = cell.Value.ToString();
}
}
File.WriteAllLines("dados.txt", conteudo);
And now, from a different form, there is another Grid that must be fill with the values saved in that File
The present 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.IO;
namespace WindowsFormsApplication31
{
public partial class Form3 : Form
{
DateTime start, end;
private void Form3_Load(object sender, EventArgs e)
{
textBox1.Text = start.ToString("dd-MM-yyyy");
textBox2.Text = end.ToString("dd-MM-yyyy");
}
public Form3(DateTime s, DateTime e)
{
InitializeComponent();
start = s;
end = e;
}
}
}
In conclusion, both of the grid should have 4 Cells:
0-Designação
1-Grupo
2-Valor
3-Data
And the second one from Form3, should read the text file, in the right order
Hope you can help me, Thanks.
Please try this below.
I have exported the grid data in to a text file as same structure as how it appears in grid as below.
private void button1_Click(object sender, EventArgs e)
{
TextWriter writer = new StreamWriter("Text.txt");
for (int i = 0; i < DataGridView1.Rows.Count; i++)
{
for (int j = 0; j < DataGridView1.Columns.Count; j++)
{
writer.Write(DataGridView1.Rows[i].Cells[j].Value.ToString() + "\t");
}
writer.WriteLine("");
}
writer.Close();
}
Created a new class with properties as the column names and a method to load the exported data into a list collection of class as shown below.Here in this example ,my grid has two columns Name and Marks.so i declared those two properties in my user class
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
namespace WindowsFormsApplication1
{
public class User
{
public string Name { get; set; }
public string Marks { get; set; }
public static List<User> LoadUserListFromFile(string path)
{
var users = new List<User>();
foreach (var line in File.ReadAllLines(path))
{
var columns = line.Split('\t');
users.Add(new User
{
Name = columns[0],
Marks = columns[1]
});
}
return users;
}
}}
Now on the form load event of second form,call the above method and bind to the second grid as shown below
private void Form2_Load(object sender, EventArgs e)
{
dataGridView2.DataSource = User.LoadUserListFromFile("Text.txt");
}
Pleas mark this as answer,if it helps.
i have created a form for a codeDOM compiler and it can compile my code if its in a single text file but i want to be able to compile the source code in the text file and a class thats in a text file so they can work together.
I am unsure how to code codeDOM to add my class file as a resource for the main source to be compiled
Heres what i have so far
codeDOM Compiler
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.CodeDom.Compiler;
using Microsoft.CSharp;
namespace CodeDOMSourceTest
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void btnCompile_Click(object sender, EventArgs e)
{
CompilerParameters Params = new CompilerParameters();
Params.GenerateExecutable = true;
Params.ReferencedAssemblies.Add("System.dll");
Params.ReferencedAssemblies.Add("TextFile1.txt");
Params.OutputAssembly = "output.exe";
string Source = Properties.Resources.CodeDOMSource;
Source = Source.Replace("[TEXT]", txtReplace.Text);
CompilerResults Results = new CSharpCodeProvider().CompileAssemblyFromSource(Params, Source);
if (Results.Errors.Count > 0)
{
foreach (CompilerError err in Results.Errors)
Console.WriteLine(err.ToString());
}
else Console.WriteLine("Compiled just fine!");
}
}
}
Source file
namespace testingCodeDOM
{
class Program
{
static void Main()
{
System.Console.WriteLine("[TEXT]");
Console.WriteLine(Testing.textwork());
System.Console.Read();
}
}
}
ClassFile
namespace testingCodeDOM
{
class Testing
{
public static string textwork()
{
string hello = "calss worked";
return hello;
}enter code here
}
}
Any ideas how to do this because i have googled it an am getting no were or at least nothing i understand
on a side not this works with with just the source but am trying to adapt it to use class files aswell
The CompileAssemblyFromSource() method can take any number of source code strings (since it's a params method). So, you can call it something like:
CompileAssemblyFromSource(Params, Source, ClassFile)
Where ClassFile is a string that contains the text of the second file.
How to create many folders in a sub-folder
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
namespace Progressbar
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
string path = #"A:\DMS\SCOSTADL";
try
{
// Determine whether the directory exists.
if (Directory.Exists(path))
{
MessageBox.Show("Paths Exists already!!!!!!!!!");
return;
}
// Try to create the directory.
DirectoryInfo di = Directory.CreateDirectory(path);
MessageBox.Show("Directory Created Successfully....!");
}
catch (Exception e)
{
Console.WriteLine("The process failed: {0}", e.ToString());
}
finally { }
}
}
}
Here in this example i am able create a folder(DMS) and sub-folder(SCOSTADL) and i want to create many sub-folders along with Sub-folder(SCOSTADL).please give me suggestions......
CreateDirectory creates all sub-directories in the path as well, so you can do Directory.CreateDirectory("C:\\abc\\def\\ghi");.