How to create a text file name with textbox value? - c#

I'm new to C#, I want to create a file with extension .txt and file name as with first three characters of textbox value.I am creating the file but i dont now how to store the file in the required destination for example c:\ Documents\ION.please help me.
Thank You For reading this...
private void button1_Click(object sender, EventArgs e)
{
button1.Text = "Create_File";
string fileName = textBox1.Text.Substring(0, 3) + ".txt";
File.Create(fileName);
MessageBox.Show("ok");
}

Thank U guys ,with all Your help I solved it
private void button2_Click(object sender, EventArgs e)
{
button2.Text = "SAVE";
var files = Directory.GetFiles(#"C:\\Users\\Apple\\Desktop\\proj").Length;
string fileName = textBox1.Text.Substring(0, 3) + -+ ++files + ".txt";
string path2 = Path.GetFullPath("C:\\Users\\Apple\\Desktop\\proj");
string docPath = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
string var = Path.Combine(docPath, path2);
string var1 = Path.Combine(var, fileName);
using (StreamWriter writer = new StreamWriter(var1))
{
string var6 = textBox1.Text;
string var7 = " ";
string var8 = textBox2.Text;
string var9 = string.Concat(var6, var7, var8);
writer.WriteLine(var9);
}
MessageBox.Show("File created");
}

string fileName = textBox.Text.Substring(0,3) + ".txt";
using(StreamWriter writer = new StreamWriter(fileName))
{
writer.WriteLine("Hello world!");
}
Note that it would be wise to confirm that the TextBox contains at least three characters before doing that.

This is the same issue i had and got it solved by doing it this way :
File.WriteAllText(folderPath + "DataExport_"+srchCat_txtbox.Text+"_"+DateTime.Now.ToString("ddMMyyyy")+".csv", csv);
I needed to save CSV files with a unique name which includes a global name "DataExport", a category name "srchCat_txtbox.Text" value and the current date.

Related

Where to put txt file in VS 2019

I have a c# script in VS 2019 and now I want to write values to a File but where do Ihave to put the .txt file? After that I want to make a Setup.exe with Inno Setup Compiler.
So my question is where do I put the file to get access to it during programming my Programm and after I installed my .exe after I installed it from the Setup.exe.
I heard something about this but I dont know what this does:
string filePath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "combinations.txt");
Now i set the Permission on top of the function as it was mention here but i still get the problem
[PermissionSet(SecurityAction.Demand, Name = "FullTrust")]
private void button4_Click(object sender, EventArgs e)
{
string date = DateTime.Now.ToString("g");
string exePath = Path.GetDirectoryName(System.Reflection.Assembly.GetEntryAssembly().Location);
string logFile = "combinations.txt";
if (File.Exists(Path.Combine(exePath, logFile)) == false)
File.Create(Path.Combine(exePath, logFile));
using (StreamWriter wr = File.AppendText(Path.Combine(exePath, logFile)))
{
wr.WriteLine(date + "|" + date);
wr.Close();
}
}
Thanks for your help
i think you can use this path correctly
it's in the folder where your exe works.
for example a writing log file in the exe folder.
in debug mode its in the debug folder.
public static void LogWrite(string mes)
{
string exepath= Path.GetDirectoryName(System.Reflection.Assembly.GetEntryAssembly().Location);
DateTime _dt = DateTime.Now;
string logFile= "Log.Inc";
if (File.Exists(Path.Combine(exepath, logFile)) == false)
File.Create(Path.Combine(exepath, logFile));
using (StreamWriter wr = File.AppendText(Path.Combine(exepath, logFile)))
{
wr.WriteLine(_dt.ToString("dd/MM/yyyy") + "|" + _dt.ToString("hh:mm") + "|" + mes);
wr.Close();
}
}
Based on my test, you can try try the following code to log the information to the txt file when you have published it.
private void button1_Click(object sender, EventArgs e)
{
string date = DateTime.Now.ToString("g");
string exePath = Path.GetDirectoryName(System.Reflection.Assembly.GetEntryAssembly().Location);
string logFile = "combinations.txt";
using (StreamWriter wr = new StreamWriter(Path.Combine(exePath, logFile), true))
{
wr.WriteLine(date + "|" + date);
wr.Close();
}
string path = Path.Combine(exePath, logFile);
MessageBox.Show(path);
}
If you use the above code, there is no need to check if the file is created.
Also, I show the path of the txt file in the final code.

Issue with output location when saving file

Currently having an issue when saving a merged word. doc to a specific location using a filebrowser dialog
// input destintion
private string[] sourceFiles;
private void browseButton_Click(object sender, EventArgs e)
{
FolderBrowserDialog diagBrowser = new FolderBrowserDialog();
diagBrowser.Description = "Select a folder which contains files needing combined...";
// Default folder, altered when the user selects folder of choice
string selectedFolder = #"";
diagBrowser.SelectedPath = selectedFolder;
// initial file path display
folderPath.Text = diagBrowser.SelectedPath;
if (DialogResult.OK == diagBrowser.ShowDialog())
{
// Grab the folder that was chosen
selectedFolder = diagBrowser.SelectedPath;
folderPath.Text = diagBrowser.SelectedPath;
sourceFiles = Directory.GetFiles(selectedFolder, "*.doc");
}
}
// output destintion
private string[] sourceFileOutput;
private void browseButtonOut_Click(object sender, EventArgs e)
{
FolderBrowserDialog diagBrowserOutput = new FolderBrowserDialog();
diagBrowserOutput.Description = "Select a folder location to save the document...";
// Default folder, altered when the user selects folder of choice
string outputFolder = #"";
diagBrowserOutput.SelectedPath = outputFolder;
// output file path display
outputPath.Text = diagBrowserOutput.SelectedPath;
if (DialogResult.OK == diagBrowserOutput.ShowDialog())
{
outputFolder = diagBrowserOutput.SelectedPath;
outputPath.Text = diagBrowserOutput.SelectedPath;
sourceFileOutput = Directory.GetFiles(outputFolder);
}
}
private void combineButton_Click(object sender, EventArgs e)
{
if (sourceFiles != null && sourceFiles.Length > 0)
{
string outputFileName = (sourceFileOutput + "Combined.docx");
MsWord.Merge(sourceFiles, outputFileName, true);
// Message displaying how many files are combined.
MessageBox.Show("A total of " + sourceFiles.Length.ToString() + " documents have been merged", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
else
{
// Message displaying error.
MessageBox.Show("Please a select a relevant folder with documents to combine", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
instead of getting the 'combined.docx' in the location chosen, i instead get a file called 'System.String[]Combined' saved on the desktop. Obviously there is something clashing regarding the name and the user selected file path.
i currently have the input folder options working however the output + file name doesn't seem to be working correctly.
any suggestions or help would be greatly appreciated, thank you.
string outputFileName = (sourceFileOutput + "Combined.docx");
This should probably read
string outputFileName = selectedFolder + "Combined.docx";
That said, please use Path.Combine to combine two parts of a path.
got the program to use the 'selected' destination.
// output destintion
string outputFolder = #"";
private void browseButtonOut_Click(object sender, EventArgs e)
{
FolderBrowserDialog diagBrowserOutput = new FolderBrowserDialog();
diagBrowserOutput.Description = "Select a folder location to save the document...";
// Default folder, altered when the user selects folder of choice
diagBrowserOutput.SelectedPath = outputFolder;
// output file path display
outputPath.Text = diagBrowserOutput.SelectedPath;
if (DialogResult.OK == diagBrowserOutput.ShowDialog())
{
outputFolder = diagBrowserOutput.SelectedPath;
outputPath.Text = diagBrowserOutput.SelectedPath;
}
}
private void combineButton_Click(object sender, EventArgs e)
{
if (sourceFiles != null && sourceFiles.Length > 0)
{
string folderFolder = outputFolder;
string outputFile = "Combined.docx";
string outputFileName = Path.Combine(folderFolder, outputFile);
MsWord.Merge(sourceFiles, outputFileName, true);
// Message displaying how many files are combined.
MessageBox.Show("A total of " + sourceFiles.Length.ToString() + " documents have been merged", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
i used the path.combine as suggested, as played around with the variables i had used.

ZipFile extracting issue

screenshot
So this is a method that gets the directory of a file (is a .JDCEDFile but its is just renamed .zip file)
With this method i try to rename het file and extract it to a specified folder.
And show its contents into the right textboxes.
This method fails at Extracting process and i don't understand why.
public void OpenEncodedFile(string path)
{
// Variabelen + verwerking
string defaultpath = Application.StartupPath + #"\temp";
string defaultzip = path;
string defaultzipRename = defaultzip.Replace(".JDCEDFile", ".zip");
File.Move(defaultzip, defaultzipRename);
ZipFile.ExtractToDirectory(defaultzipRename, defaultpath);
Input.Text = File.ReadAllText(defaultpath + #"\tempData.txt");
Password.Text = File.ReadAllText(defaultpath + #"\tempPass.txt");
File.Move(defaultzipRename, defaultzip);
}
"path" has to be wrong, I just tested it and it worked fine.
private void openEncodedFileToolStripMenuItem_Click(object sender, EventArgs e)
{
if (openEncodedFileDialog.ShowDialog() == DialogResult.OK)
{
OpenEncodedFile(openEncodedFileDialog.FileName);
}
}
This the the code.

How to Restore MS Access database zip file in C# winForms?

I have this backup and restore code in C# using MS Access as its database. I finished doing the backup in zip format and now I want to restore the Zipped file. Any help will be much appreciated.
public void BackupDatabase(string dateToday)
{
string dbFileName = "dbCPS.accdb";
string CurrentDatabasePath = Path.Combine(Environment.CurrentDirectory , dbFileName);
string backTimeStamp = Path.GetFileNameWithoutExtension(dbFileName) + "_" + dateToday + ".zip";// +Path.GetExtension(dbFileName);
string destFileName = backTimeStamp;// +dbFileName;
FolderBrowserDialog fbd = new FolderBrowserDialog();
if (fbd.ShowDialog() == DialogResult.OK)
{
string PathtobackUp = fbd.SelectedPath.ToString();
destFileName = Path.Combine(PathtobackUp, destFileName);
//File.Copy(CurrentDatabasePath, destFileName, true);
using (var zip = new ZipFile())
{
zip.AddFile(dbFileName);
zip.Save(destFileName);
}
MessageBox.Show("Backup successful! ");
}
}
private void backupToolStripMenuItem1_Click(object sender, EventArgs e)
{
BackupDatabase(DateTime.Now.ToString("ddMMMyyyy_HH.mm"));
}
public void RestoreDatabase(string restoreFile)
{
string dbFileName = "dbCPS.accdb";
string pathBackup = restoreFile;
string CurrentDatabasePath = Path.Combine(Environment.CurrentDirectory, dbFileName);
File.Copy(pathBackup, CurrentDatabasePath, true);
MessageBox.Show("Restore successful! ");
}
private void restoreToolStripMenuItem_Click(object sender, EventArgs e)
{
try
{
openFileDialogBackUp.FileName = "dbCPS";
openFileDialogBackUp.InitialDirectory = AppDomain.CurrentDomain.BaseDirectory + #"Sauvegardes";
if (openFileDialogBackUp.ShowDialog() == DialogResult.OK)
RestoreDatabase(openFileDialogBackUp.FileName);
}
catch (Exception error)
{
MessageBox.Show(error.ToString());
}
}
This code extracts the zipped file but I dont know how to do the restore at the same time.
using (ZipFile zip = ZipFile.Read(restoreFile))
{
zip.ExtractAll(#"C:\Users\Desktop\backup");
}
According to the MSDN documentation here, you should be able to extract the zip file directly to the destination folder. Your existing "restore" code simply does a file copy to CurrentDatabasePath, so one would expect that a statement like...
System.IO.Compression.ZipFile.ExtractToDirectory(pathToZipFile, CurrentDatabasePath);
...would be all it takes. (I would test it myself, but ZipFile was apparently added in .NET 4.5 and my copy of Visual Studio is too old.)

Can't access file

I can't seem to get access to the file I'm working with in the program I'm writing. I'm not sure how exactly to work this since I want my program to open a file of your choice, which it does, then I want it to be able to take in info into an arrary, which it does, then from there, write that information from the array to the file you opened up. When I try some code to start working on it it tells me, "The process cannot access the file 'file' because it is being used by another process." Here is what I have so far. Please let me know. Thank you. The problematic areas is the Save_Click section of the code where I wrote "This is a test" Thanks.
public partial class ListingSearch : Form
{
string line;
DialogResult result;
string fileName;
int i = 0;
string[] first = new string[100];
string[] last = new string [100];
string[] phone = new string [100];
string[] grade = new string [100];
public ListingSearch()
{
InitializeComponent();
MessageBox.Show("Please be sure to open a file before beginning");
}
private void OpenFile_Click(object sender, EventArgs e)
{
using (OpenFileDialog filechooser = new OpenFileDialog())
{
result = filechooser.ShowDialog();
fileName = filechooser.FileName;
System.IO.StreamReader file =
new System.IO.StreamReader(fileName);
while ((line = file.ReadLine()) != null)
{
string[] words = File.ReadAllText(fileName).Split(new string[] { "\n", "\r\n", ":" }, StringSplitOptions.RemoveEmptyEntries);
//firstName.Text = words[4];
//lastName.Text = words[5];
//telephone.Text = words[6];
//GPA.Text = words[7];
}
Read.Enabled = true;
}
}
private void Save_Click(object sender, EventArgs e)
{
File.AppendAllText(fileName, "This is a test");
}
private void Read_Click(object sender, EventArgs e)
{
MessageBox.Show(fileName);
MessageBox.Show(File.ReadAllText(fileName));
}
private void info_Click(object sender, EventArgs e)
{
first[i] = firstName.Text;
firstName.Text = " ";
last[i] = lastName.Text;
lastName.Text = " ";
phone[i] = telephone.Text;
telephone.Text = " ";
grade[i] = GPA.Text;
GPA.Text = " ";
i++;
}
private void displayinfo_Click(object sender, EventArgs e)
{
if (i == 0)
MessageBox.Show("Nothing to display!");
else
for (int j = 0; j < i; j++)
{
MessageBox.Show(first[j] + " " + last[j] + "\r" + phone[j] + "\r" + grade[j]);
}
}
You get error here
File.ReadAllText(fileName)
because you open same file before it here
System.IO.StreamReader file = new System.IO.StreamReader(fileName);
You need to close the file after you are finished reading it. Also, not sure why you are opening the file at all, since you subsequently use File.ReadAllText which will handle opening and closing the file all on its own.
Seems like your OpenFile_click event should just look like this:
using (OpenFileDialog filechooser = new OpenFileDialog())
{
result = filechooser.ShowDialog();
fileName = filechooser.FileName;
string[] words = File.ReadAllText(fileName).Split(new string[] { "\n", "\r\n", ":" }, StringSplitOptions.RemoveEmptyEntries);
Read.Enabled = true;
}
You haven't closed your StreamReader. C# will lock the file until you do. Or you could use a StreamWriter after you closed your StreamReader

Categories

Resources