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();
}
}
}
Related
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.
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.
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);
}
}
}
}
following code implements an Access-Connection using an OpenFileDialog.
My Question:
How should I change the class in order to use this Access-Connection at each point in each formular. Unfortunatley, C# doesn't use global variables.....
using System;
using System.Data;
using System.Data.OleDb;
using System.Windows.Forms;
using System.IO;
namespace Access
{
public class AccessConnection
{
OpenFileDialog ofd = new OpenFileDialog();
public string Verbinden()
{
string path = #"C:\Users\Projects\C#\C#_GUI\ACCESS_DataGrid";
if (Directory.Exists(path)) ofd.InitialDirectory = #"C:\Users\ACCESS_DataGrid";
else ofd.InitialDirectory = "C:\\";
ofd.Filter = "Accesdatenbanken|*.mdb";
string connection = "";
if (MessageBox.Show("\tLoad Access-Database now?", "Title", MessageBoxButtons.YesNo) == DialogResult.Yes)
{
if (ofd.ShowDialog() == DialogResult.OK)
{
connection = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source= " + ofd.FileName;
}
else Application.Exit();
}
else Application.Exit();
return connection;
}
}
}
Perhaps, you can make the class and the method "static". If, then you have one instance of the class in the whole application, like a global variable.
I have a Windows Forms Application with a CheckBox and a button. The button will make it so the CodeDOM compiled exe will disable task manager. But if they don't want it to disable, they can uncheck the button. What I'm trying to to is make it so if they uncheck the button it will remove the block of code from the resource file that disables task manager.
This is my resource file:
using System;
using System.Windows.Forms;
using Microsoft.Win32;
static class Program
{
[STAThread]
static void Main()
{
RegistryKey regkey;
string keyValueInt = "1";
string subKey = "Software\\Microsoft\\Windows\\CurrentVersion\\Policies\\System";
try
{
regkey = Registry.CurrentUser.CreateSubKey(subKey);
regkey.SetValue("DisableTaskMgr", keyValueInt);
regkey.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
}
My main 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.CodeDom.Compiler;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
string source = Properties.Resources.BaseSource;
if (checkBox1.Checked == false)
{
// Not sure what to put here
}
CompilerResults results = null;
using (SaveFileDialog sfd = new SaveFileDialog() { Filter = "Executable|*.exe"})
{
if (sfd.ShowDialog() == DialogResult.OK)
{
results = Build(source, sfd.FileName);
}
}
if (results.Errors.Count > 0)
foreach (CompilerError error in results.Errors)
Console.WriteLine("{0} at line {1}",
error.ErrorText, error.Line);
else
Console.WriteLine("Succesfully compiled!");
Console.ReadLine();
}
private static CompilerResults Build(string source, string fileName)
{
CompilerParameters parameters = new CompilerParameters()
{
GenerateExecutable = true,
ReferencedAssemblies = { "System.dll", "System.Windows.Forms.dll" },
OutputAssembly = fileName,
TreatWarningsAsErrors = false
};
CodeDomProvider provider = CodeDomProvider.CreateProvider("CSharp");
return provider.CompileAssemblyFromSource(parameters, source);
}
}
}
Instead of replacing part of the source code yourself, you could let the compiler do it for you by leveraging conditional compilation symbols.
You would modify your source file to include a conditional compilation symbol, e.g. DISABLETASKMGR, like this:
using System;
using System.Windows.Forms;
using Microsoft.Win32;
static class Program
{
[STAThread]
static void Main()
{
#if DISABLETASKMGR
RegistryKey regkey;
string keyValueInt = "1";
string subKey = "Software\\Microsoft\\Windows\\CurrentVersion\\Policies\\System";
try
{
regkey = Registry.CurrentUser.CreateSubKey(subKey);
regkey.SetValue("DisableTaskMgr", keyValueInt);
regkey.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
#endif
}
}
Then you set the CompilerOptions based on whether your check box is checked:
private static CompilerResults Build(string source, string fileName, bool disableTaskManager)
{
CompilerParameters parameters = new CompilerParameters()
{
CompilerOptions = disableTaskManager ? "/define:DISABLETASKMGR" : "",
GenerateExecutable = true,
ReferencedAssemblies = { "System.dll", "System.Windows.Forms.dll" },
OutputAssembly = fileName,
TreatWarningsAsErrors = false
};
CodeDomProvider provider = CodeDomProvider.CreateProvider("CSharp");
return provider.CompileAssemblyFromSource(parameters, source);
}
This is probably going to be more maintainable than solutions based on text replacements or insertions later. Of course, still another option is to have two source files (one with the optional code and one without it) and select the appropriate one based on the settings selected by the user.