Global access for user's File - c#

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.

Related

Folder Dialog return to dialog if criteria not met

I'm using the Ookii Vista folder dialog for ease of use, and I have this code going on which is called from a button:
using System;
using System.IO;
using System.Linq;
using System.Windows.Forms;
using Ookii.Dialogs;
private string LoadDirectories()
{
VistaFolderBrowserDialog fbd = new VistaFolderBrowserDialog();
if (fbd.ShowDialog() == DialogResult.OK && fbd.SelectedPath.Contains("U000"))
{
return fbd.SelectedPath;
}
else
{
MessageBox.Show("Folder must be root assembly, which has U000 in name");
}
return string.Empty;
}
Currently, if the user does not pick a folder with U000 in the name, the dialog will close, but I want it to stay open until user either cancels or sets the correct folder path. I can't find this anywhere.
A simple realization of your needs (Add a while):
Used nuget: Ookii.Dialogs.Wpf
private string LoadDirectories()
{
VistaFolderBrowserDialog fbd = new VistaFolderBrowserDialog();
while (true)
{
if (fbd.ShowDialog() == false)
{
break;
}
else if (fbd.SelectedPath.Contains("U000"))
{
return fbd.SelectedPath;
}
else
{
MessageBox.Show("Folder must be root assembly, which has U000 in name");
}
}
return string.Empty;
}
output:

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

select multiple xml files using file dialog and saving them

HI I have several xml files , I select them using open file dialog, then delete duplicate data from those files and now I wanted every individual files to saved as.bak file I can select multiple files and delete those data from files but dont no how to save those files after deleting.
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.Xml;
using System.Xml.Linq;
using System.IO.Path;
namespace XML_Deletes
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button2_Click(object sender, EventArgs e)
{
//single indivual file
var doc = XDocument.Load(#"C:\\Users\IT-Administrator\Desktop\21.xml");
doc.Root.Elements("Incident")
.GroupBy(s => (string)s.Element("Comment"))
.SelectMany(g => g.Skip(1))
.Remove();
//doc.Save(#"C:\Users\IT-Administrator\Desktop\22.xml");
}
private void button1_Click(object sender, EventArgs e)
{
OpenFileDialog openFileDialog1 = new OpenFileDialog();
openFileDialog1.Filter = "XML files(.xml)|*.xml|all Files(*.*)|*.*";
openFileDialog1.FilterIndex = 1;
openFileDialog1.Multiselect = true;
if(openFileDialog1.ShowDialog() == DialogResult.OK)
{
{
if (!String.Equals(Path.GetExtension(openFileDialog1.FileName),
".xml",
StringComparison.OrdinalIgnoreCase))
{
// Invalid file type selected; display an error.
MessageBox.Show("The type of the selected file is not supported by this application. You must select an XML file.",
"Invalid File Type",
MessageBoxButtons.OK,
MessageBoxIcon.Error);
}
else
{
}
} }
}
}
Are you looking for XDocument.Save?
doc.Save(#"C:\\Users\IT-Administrator\Desktop\21.xml");
That's already in your code (though its commented out?). Are you having issues saving?

MessageBox not showing (focused) after SaveFileDialog

For some reason after my SaveFileDialog, my app will never show the MessageBox. Is there something I'm missing? Or is this a threading issue?
I run the application as a Windows Form application using VS 2010 Express.
I do not get any exceptions.
To add: When I step through the code, all seems to go well. Which is weird, so I believe it is a timing issue.
Pointed out by LarsTech and others, the MessageBoxes do show up, however the focus is gone; in other words the MessageBox is pushed behind other windows or minimized. This is a problem.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Globalization;
using System.IO;
namespace SpeedDating
{
class Program
{
[STAThread]
static void Main(string[] args)
{
string filename = "test.test"; // args[0];
string ext = filename.Substring(filename.LastIndexOf('.'));
SaveFileDialog dialog = new SaveFileDialog();
dialog.Title = "SpeedDating App";
dialog.RestoreDirectory = true;
dialog.CheckFileExists = false;
dialog.CheckPathExists = false;
dialog.FileName = DateTime.Now.ToString("yyyyMMdd") + ext;
DialogResult result = dialog.ShowDialog();
if (result == DialogResult.OK && dialog.FileName != "")
{
try
{
FileStream outfs = File.Create(dialog.FileName);
FileStream infs = File.Open(filename, FileMode.Open);
infs.CopyTo(outfs);
infs.Close();
outfs.Close();
}
catch (NotSupportedException ex)
{
MessageBox.Show("Probably removed the original file.");
}
}
else
{
MessageBox.Show("No path found to write to.");
}
MessageBox.Show("I came here and all I got was this louzy printline");
}
}
}
I tried this one and it showed right away:
MessageBox.Show(new Form() { WindowState = FormWindowState.Maximized, TopMost = true }, "You clicked Cancel button", "Cancel");
Try this for your Message Box.
MessageBox.Show(this,"Probably removed the original file.");
I created a new project and pasted your code and it works for me. Make sure you have done a full rebuild before running. Also, with this line:
dialog.FileName = DateTime.Now.ToString(format) + "." + ext;
The dialog box will have a file name to begin with. Therefore, only hitting the cancel button (assuming you don't clear the save dialog first) will trigger the message box. Either way, I got the message box to pop up by failing your IF test either way. Your code looks alright.
Perhaps you should put the SaveFileDialog in a using to ensure its disposal prior to the MessageBox call:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Globalization;
using System.IO;
namespace SpeedDating
{
class Program
{
[STAThread]
static void Main(string[] args)
{
string filename = "test.test"; // args[0];
string ext = filename.Substring(filename.LastIndexOf('.'));
using (SaveFileDialog dialog = new SaveFileDialog())
{
dialog.Title = "SpeedDating App by K.Toet";
dialog.RestoreDirectory = true;
dialog.CheckFileExists = false;
dialog.CheckPathExists = false;
dialog.FileName = DateTime.Now.ToString("yyyyMMdd") + ext;
DialogResult result = dialog.ShowDialog();
if (result == DialogResult.OK && dialog.FileName != "")
{
try
{
FileStream outfs = File.Create(dialog.FileName);
FileStream infs = File.Open(filename, FileMode.Open);
infs.CopyTo(outfs);
infs.Close();
outfs.Close();
}
catch (NotSupportedException ex)
{
MessageBox.Show("Probably removed the original file.");
}
}
else
{
MessageBox.Show("No path found to write to.");
}
}
MessageBox.Show("I came here and all I got was this louzy printline");
}
}
}

Categories

Resources