c# How to have user select folder and then enter - c#

I am fairly new to C# so i don't know how to attack this problem. I have this code, that generates the form so a pop up box comes up and lets you select the folder the user wants to select. The problem is that after its selected it doesn't give an option to hit enter or hit ok so that the rest of my code can use that folder as a path to execute the remainder of what i want to do.
This is the code:
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 PdfSharp.Pdf;
using PdfSharp.Pdf.IO;
using System.IO;
namespace FolderBrowserDialogSampleInCSharp
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void BrowseFolderButton_Click(object sender, EventArgs e)
{
FolderBrowserDialog folderDlg = new FolderBrowserDialog();
folderDlg.ShowNewFolderButton = true;
// Show the FolderBrowserDialog.
DialogResult result = folderDlg.ShowDialog();
if (result == DialogResult.OK)
{
textBox1.Text = folderDlg.SelectedPath;
Environment.SpecialFolder root = folderDlg.RootFolder;
var dir = textBox1.Text;
File.SetAttributes(dir, FileAttributes.Normal);
string[] files = Directory.GetFiles(dir, "*.pdf");
IEnumerable<IGrouping<string, string>> groups = files.GroupBy(n => n.Split('.')[0].Split('_')[0]);
foreach (var items in groups)
{
Console.WriteLine(items.Key);
PdfDocument outputPDFDocument = new PdfDocument();
foreach (var pdfFile in items)
{
Merge(outputPDFDocument, pdfFile);
}
if (!Directory.Exists(dir + #"\Merge"))
Directory.CreateDirectory(dir + #"\Merge");
outputPDFDocument.Save(Path.GetDirectoryName(items.Key) + #"\Merge\" + Path.GetFileNameWithoutExtension(items.Key) + ".pdf");
}
Console.ReadKey();
}
}
private static void Merge(PdfDocument outputPDFDocument, string pdfFile)
{
PdfDocument inputPDFDocument = PdfReader.Open(pdfFile, PdfDocumentOpenMode.Import);
outputPDFDocument.Version = inputPDFDocument.Version;
foreach (PdfPage page in inputPDFDocument.Pages)
{
outputPDFDocument.AddPage(page);
}
}
}
}
What generates the form to come is :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
namespace FolderBrowserDialogSampleInCSharp
{
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
}
}
I'm assuming that i either have to add in a button in the form design as "enter" or "ok."
Could i just have this so that as soon as the user selects the folder and hits ok the program proceeds to store that as the user selected path?

The answer i was searching for:
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 PdfSharp.Pdf;
using PdfSharp.Pdf.IO;
using System.IO;
namespace FolderBrowserDialogSampleInCSharp
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void BrowseFolderButton_Click(object sender, EventArgs e)
{
FolderBrowserDialog folderDlg = new FolderBrowserDialog();
folderDlg.ShowNewFolderButton = true;
// Show the FolderBrowserDialog.
DialogResult result = folderDlg.ShowDialog();
if (result == DialogResult.OK)
{
textBox1.Text = folderDlg.SelectedPath;
Environment.SpecialFolder root = folderDlg.RootFolder;
var dir = textBox1.Text;
File.SetAttributes(dir, FileAttributes.Normal);
string[] files = Directory.GetFiles(dir, "*.pdf");
IEnumerable<IGrouping<string, string>> groups = files.GroupBy(n => n.Split('.')[0].Split('_')[0]);
foreach (var items in groups)
{
Console.WriteLine(items.Key);
PdfDocument outputPDFDocument = new PdfDocument();
foreach (var pdfFile in items)
{
Merge(outputPDFDocument, pdfFile);
}
if (!Directory.Exists(dir + #"\Merge"))
Directory.CreateDirectory(dir + #"\Merge");
outputPDFDocument.Save(Path.GetDirectoryName(items.Key) + #"\Merge\" + Path.GetFileNameWithoutExtension(items.Key) + ".pdf");
}
Console.Read();
Close();
}
}
private static void Merge(PdfDocument outputPDFDocument, string pdfFile)
{
PdfDocument inputPDFDocument = PdfReader.Open(pdfFile, PdfDocumentOpenMode.Import);
outputPDFDocument.Version = inputPDFDocument.Version;
foreach (PdfPage page in inputPDFDocument.Pages)
{
outputPDFDocument.AddPage(page);
}
}
}
}

Related

Incorrect reading of an array

I am working in c-sharp .net and I am working on creating a login screen for my project. I have a text file with login info for all the users. My c-sharp scrip reads that file to a string then cuts it up into two lists, _usernames and _passwords. When the user types their login info and hits login the _usernames[0] and _passwords[0] account info are the only ones that work. What I want it to do is look through all the _usernames for the inputted one, if it finds it then check the _password[same index as _usernames] and if both are the same as what the user submitted then it will add "true" to the richTextBox.
Why is it not correctly reading from the array?
This is my users.txt:
admin,test|
andrew,yeet|
zana,happy|
This is my c-sharp script:
using System;
using System.IO;
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 BaseUserInterfase
{
public partial class Login : Form
{
string path = Directory.GetCurrentDirectory() + "\\data\\users.txt";
string data;
string[] _usernames = new string[10];
string[] _passwords = new string[10];
public Login()
{
InitializeComponent();
}
private void Login_Load(object sender, EventArgs e)
{
GetLoginData();
}
private void btnLogin_Click(object sender, EventArgs e)
{
rtbTemp.Text = "";
for(int i = 0; i < _usernames.Length; i++)
{
if(_usernames[i] == null)
{
break;
}
rtbTemp.AppendText("\n" + _usernames[i]);
rtbTemp.AppendText("\n" + tbUsername.Text.ToString());
rtbTemp.AppendText("\n" + _passwords[i]);
rtbTemp.AppendText("\n" + tbPassword.Text.ToString());
if (_usernames[i] == tbUsername.Text.ToString())
{
rtbTemp.AppendText("\nUsername true");
if (_passwords[i] == tbPassword.Text.ToString())
{
rtbTemp.AppendText("\nPassword true");
rtbTemp.AppendText("\ntrue");
return;
}
}
}
rtbTemp.AppendText("\nfalse");
}
public void GetLoginData()
{
using (StreamReader streamReader = new StreamReader(path, Encoding.UTF8))
{
data = streamReader.ReadToEnd();
}
List<string> _data = data.Split('|').ToList();
_data.RemoveAt(_data.Count - 1);
rtbTemp.AppendText("\n");
Array.Resize<string>(ref _usernames, _data.Count);
Array.Resize<string>(ref _passwords, _data.Count);
foreach (string _item in _data)
{
List<string> userdata = _item.Split(',').ToList();
string username = userdata[0].ToString();
string password = userdata[1].ToString();
Console.WriteLine(_item);
Console.WriteLine(username);
Console.WriteLine(password);
for(int i = 0; i < _data.Count; i++)
{
if(_usernames[i] == null)
{
_usernames[i] = username;
_passwords[i] = password;
break;
}
}
}
}
private void btnExit_Click(object sender, EventArgs e)
{
Application.Exit();
}
}
}
And this is an image of the login screen:
1
Your file contains carriage return characters. Remove them before you split its content
data = streamReader.ReadToEnd().Replace("\r\n", "");

cannot convert from 'System.Management.EnumerationOptions' to 'System.IO.SearchOption

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 Microsoft.VisualBasic.FileIO;
using System.Management;
namespace test_code
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
FolderBrowserDialog folderDlg = new FolderBrowserDialog();
//folderDlg.ShowDialog();
if (folderDlg.ShowDialog() != DialogResult.OK)
{
return;
}
// Has different framework dependend implementations
// in order to handle unauthorized access to subfolders
RenamePngFiles(folderDlg.SelectedPath);
}
private void RenamePngFiles(string directoryPath)
{
int fileNameSuffixCounter = 1;
foreach (string originalFullFileName in System.IO.Directory.EnumerateFiles(directoryPath, "*.png", new EnumerationOptions()))
{
// The new file name without path
var newFileName = $"{System.IO.Path.GetFileNameWithoutExtension(originalFullFileName)}#{fileNameSuffixCounter++}{System.IO.Path.GetExtension(originalFullFileName)}";
FileSystem.RenameFile(originalFullFileName, newFileName);
}
}
}
}
Above is my code and I am not sure why i am not able to remove the above error. I tried all sorts of namespace and i cannot of get rid of it. I am using .netframework 4.7.2.
AS you can see all I am trying to do is rename all the files in a folder including subfolder to append with # and a number which keep on increasing depending on the number of files in a folder.
Combined with the comments above, I made the following changes.
Updated:
Modify all png files in the selectedPath.
RenameAllPngFiles(folderDlg.SelectedPath);
The following are custom functions:
Rename all png files :
private void RenameAllPngFiles(string directoryPath) {
RenameCurrentPng(directoryPath);
foreach (var item in GetDirectoryInfos(directoryPath)) {
RenameCurrentPng(item.FullName);
}
}
Rename all png files in the current directory:
private void RenameCurrentPng(string directoryPath) {
int fileNameSuffixCounter = 1;
foreach (string originalFullFileName in Directory.EnumerateFiles(directoryPath, "*.png")) {
// The new file name without path
var newFileName = $"{System.IO.Path.GetFileNameWithoutExtension(originalFullFileName)}#{fileNameSuffixCounter++}{System.IO.Path.GetExtension(originalFullFileName)}";
FileSystem.RenameFile(originalFullFileName, newFileName);
}
}
Get the addresses of all subfolders :
private DirectoryInfo[] GetDirectoryInfos(string directoryPath) {
DirectoryInfo di = new DirectoryInfo(directoryPath);
DirectoryInfo[] directories = di.GetDirectories("*", System.IO.SearchOption.AllDirectories);
return directories;
}
If you have questions about my code, please comment below and I will follow up.

Access to file denied in C# .NET 3.1 forms

Hello I was writing a basic text editor in C# on visual studio windows form using the .NET framework 3.1 long term support version everything worked fine until I wrote the save file script
Here's the code for "Form1.cs" which is where the open and save file functions reside
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;
using System.Security.Principal;
namespace Text_Editor
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
string locsave;
private void openbtn_Click(object sender, EventArgs e)
{
var identity = WindowsIdentity.GetCurrent();
var principal = new WindowsPrincipal(identity);
if (principal.IsInRole(WindowsBuiltInRole.Administrator) != true)
{
MessageBox.Show("Run as Admin");
System.Windows.Forms.Application.ExitThread();
}
else
{
OpenFileDialog openfile = new OpenFileDialog();
if (openfile.ShowDialog() == DialogResult.OK)
{
var locationArray = openfile.FileName;
string location = "";
locsave = locationArray;
foreach (char peice in locationArray)
{
location = location + peice;
}
var contentArray = File.ReadAllText(location);
string content = "";
label4.Text = location;
foreach (char peice in contentArray)
{
content = content + peice;
}
richTextBox1.Text = content;
}
}
}
private void Form1_Load(object sender, EventArgs e)
{
Console.WriteLine("Test");
}
private void savebtn_Click(object sender, EventArgs e)
{
if (#label4.Text == "")
{
MessageBox.Show("Open a text file first");
}
else
{
StreamWriter outputfile = new StreamWriter(locsave);
outputfile.Write(richTextBox1.Text); //this is where the error occures and it throws the error of access denyed
outputfile.Close();
}
}
}
}
Does anyone have a suggestion about what to do I looked around on google for a solution but it seemed most did not work and some others I did not understand.

How to use ShowFileDialog in Console Application c#

How can I assign filepath to the string file123 using ShowFileDialog();
List<string> lines = File.ReadAllLines(file123).ToList();
foreach(string line in lines)
{
Console.WriteLine(line);
}
What you need.
first Add
using System.Windows.Forms;
to your console project;
then you need to mark
[STAThread]
above your main method.
and tested code below
[STAThread]
static void Main(string[] args)
{
string xyz = string.Empty;
OpenFileDialog openFileDialog = new OpenFileDialog();
DialogResult result = openFileDialog.ShowDialog();
if (result == DialogResult.OK)
xyz = openFileDialog.FileName;
Console.WriteLine(xyz);
Console.ReadKey();
}
First you have to add a refrence to System.Windows.Forms.dll for this to work
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms; // Required to use OpenFileDialog.
using System.IO; // Required to read/write to files.
namespace ConsoleApp1
{
class Program
{
[STAThread] // This attribute is required to access OLE related functions.
static void Main(string[] args)
{
OpenFileDialog openFileDialog1 = new OpenFileDialog();
openFileDialog1.Multiselect = false;
string file123 = "";
if (openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{ file123 = openFileDialog1.FileName; }
List<string> lines = File.ReadAllLines(file123).ToList();
foreach (string line in lines)
{ Console.WriteLine(line); }
Console.ReadKey();
}
}
}

How can i check if a text file contain more then one line of text inside?

I have this code:
BeginInvoke(new Action(() => tempNamesAndTexts.ForEach(Item => textBox1.AppendText(DateTime.Now + "===> " + Item + Environment.NewLine))));
foreach (string items in tempNamesAndTexts)
{
Logger.Write(items);
}
Once im running the program it will do: Logger.Write(items);
Then the text file will look like:
Danie hello
Ron hi
Yael bye
Josh everyone ok
Next time im running the program it will write to the text file the same strings.
I want to check if this string already exist in the text file dont write them again else do write so the result will be that each time im running the program it will write to the logger(text file) only new strings if there are any.
This is the string variable of the logger text file:
full_path_log_file_name
This variable inside have:
C:\\Users\\Chocolade\\AppData\\Local\\ChatrollLogger\\ChatrollLogger\\log\\logger.txt
This is the complete code untill this part wich is the part that DoWork always do one time when im running the program:
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.Net;
using System.IO;
using System.Text.RegularExpressions;
using System.Threading;
using DannyGeneral;
namespace ChatrollLogger
{
public partial class Form1 : Form
{
string log_file_name = #"\logger.txt";
string full_path_log_file_name;
string path_log;
bool result;
List<string> namesAndTexts;
WebResponse response;
StreamReader reader;
string profileName;
string profileNameText;
string url;
string testingUrl;
int index;
List<string> names;
List<string> texts;
WebClient wc;
public Form1()
{
InitializeComponent();
Logger.exist();
wc = new WebClient();
result = true;
url = "http://chatroll.com/rotternet";
testingUrl = "http://chatroll.com/testings";
backgroundWorker1.RunWorkerAsync();
path_log = Path.GetDirectoryName(Application.LocalUserAppDataPath) + #"\log";
full_path_log_file_name = path_log + log_file_name;
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
BackgroundWorker worker = sender as BackgroundWorker;
List<string> tempNamesAndTexts = new List<string>();
string tempDownload = downloadContent();
GetProfileNames(tempDownload);
GetTextFromProfile(tempDownload);
for (int i = 0; i < names.Count; i++)
{
tempNamesAndTexts.Add(names[i] + " " + texts[i]);
}
if (InvokeRequired)
{
BeginInvoke(new Action(() => tempNamesAndTexts.ForEach(Item => textBox1.AppendText(DateTime.Now + "===> " + Item + Environment.NewLine))));
foreach (string items in tempNamesAndTexts)
{
Logger.Write(items);
string t = full_path_log_file_name;
}
}
Something like this?
string path = "test.txt";
string valueToWrite = "....";
//only write to the file, if the specified string is not already there
if(!File.ReadLines(path).Any(l => string.Equals(l, valueToWrite)))
{
File.AppendAllText(path, valueToWrite);
}
Use File.ReadAllLines
string[] array = File.ReadAllLines("test.txt");
if(array.Length > 0)
{
// lines exist
}

Categories

Resources