My form doesn't load if I have this bit of code in it
private void Form1_Load(object sender, EventArgs e)
{
// Variables
string currentDirectory = Directory.GetCurrentDirectory();
string checkFile = ("mailingdir\\check.txt");
bool newFolder = (File.Exists(checkFile));
if (newFolder)
{
newFolder = true;
}
else
{
newFolder = false;
File.Create("mailingdir\\check.txt");
}
If I comment out the File.Create("mailingdir\\check.txt"); it loads right up.
I am just experimenting, so I think I am making a beginner mistake.
Code above works perfectly as long as path exsists. Replace "mailingdir" with dot so it will refer to location of app. Looks like there is no "mailingdir" where exe is located.
private void Form1_Load(object sender, EventArgs e)
{
string currentDirectory = Directory.GetCurrentDirectory();
string workingDirectoryPlus1 = (currentDirectory + 1);
string checkFile = (".\\check.txt");
bool newFolder = (File.Exists(checkFile));
if (newFolder)
{
newFolder = true;
}
else
{
newFolder = false;
File.Create(".\\check.txt");
}
}
Your code gives a DirectoryNotFoundException because mailingdir doesn't exist.
you must create the directory first, then the file.
Directory.CreateDirectory("mailingdir");
File.Create("mailingdir\\check.txt");
Related
I tried to use the method
System.IO.File.Move(sourceFile,newFilePath);
to rename a File, but I always get the same error message, that my file couldn't be found.
I tried to manually write the source Path
System.IO.File.Move(#"D:\Users\XXX\Desktop\TestOrHMoin",#"D:\Users\XXX\Desktop\TestOrHMoinNEW");
but I still get the same ERROR Message.
This is my full code
`
private void button1_Click(object sender, EventArgs e)
{
OpenFileDialog openfiledialog = new OpenFileDialog();
if (openfiledialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
oldFilePath = openfiledialog.FileName;
listBox1.Items.Add(oldFilePath);
}
}
private void button2_Click(object sender, EventArgs e)
{
newFilePath = textBox1.Text;
oldFilePath = oldFilePath.Remove(oldFilePath.Length-newFilePath.Length);
newFilePath = oldFilePath + newFilePath;
string sourceFile = #oldFilePath;
string newFile = #newFilePath;
MessageBox.Show(sourceFile);
System.IO.File.Move(sourceFile,newFilePath);
// This part is the real code, the above Part is for debugging/testing
//System.IO.FileInfo fi = new System.IO.FileInfo(sourceFile);
//if (fi.Exists)
//{
// fi.MoveTo(newFilePath);
// MessageBox.Show("Erfolgreich geƤndert");
//} else { MessageBox.Show("Abbruch"); }
}
`
oldFilePath = oldFilePath.Remove(oldFilePath.Length-newFilePath.Length);
was wrong
I needed to declare another variable, so oldFilePath gets untouched. It was my error. I still don't know, why the manuell direction got an error.
I am trying to output the file address of an item selected in a combobox. But i keep getting the Directory address of the project and not the item itself. Please help. Here is my Code:
private void comboBox1_SelectedIndexChanged_1(object sender, EventArgs e)
{
if (availableSoftDropBox.SelectedItem.Equals("Choose Your Own..."))
{
if (openFileDialog1.ShowDialog() == DialogResult.OK)
txtFlashFile.Text = openFileDialog1.FileName;
}
else
{
string fileName;
fileName = Path.GetFullPath((string)availableSoftDropBox.SelectedItem);
string fullPath = #"C:\Program Files (x86)\yeet-n . master\yeet-
master\src\yeet\System\Products\" + (fileName);
txtFlashFile.Text = fullPath;
I'm not quite sure what you want to achieve, but using FileInfo instead of Path.GetFullPath might help.
private void comboBox1_SelectedIndexChanged_1(object sender, EventArgs e)
{
const string fullPath = #"C:\Program Files (x86)\yeet-n . master\yeet-
master\src\yeet\System\Products\";
string selection = (string)availableSoftDropBox.SelectedItem;
var fileInfo = new FileInfo(fullPath + selection);
string text = fileInfo.FullName;
if (selection.Equals("Choose Your Own..."))
{
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
text = openFileDialog1.FileName;
}
}
txtFlashFile.Text = text;
}
I'm creating simple launcher for my other application and I need advise on logical part of the program. Launcher needs to check for connection, then check for file versions (from site), compare it with currently downloaded versions (if any) and if everything is alright, start the program, if not, update (download) files that differs from newest version. The files are:
program.exe, config.cfg and mapFolder. The program.exe and mapFolder must be updated, and config.cfg is only downloaded when there is no such file. Additionaly mapFolder is an folder which contains lots of random files (every new version can have totally different files in mapFolder).
For the file version I thought I would use simple DownloadString from my main site, which may contain something like program:6.0,map:2.3, so newest program ver is 6.0 and mapFolder is 2.3. Then I can use FileVersionInfo.GetVersionInfo to get the version of current program (if any) and include a file "version" into mapFolder to read current version.
The problem is I dont know how to download whole folder using WebClient and what's the best way to do what I want to do. I've tried to download the mapFolder as zip and then automatically unpack it, but the launcher need to be coded in .net 3.0.
Here is my current code, that's just a prototype to get familiar with whole situation, dont base on it.
`
WebClient wc = new WebClient();
string verifySite = "google.com/downloads/version";
string downloadSite = "google.com/downloads/program.exe";
Uri verifyUri, downloadUri = null;
string userVer, currVer = "";
string downloadPath = Directory.GetCurrentDirectory();
string clientName = "program.exe";
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
wc.DownloadFileCompleted += new AsyncCompletedEventHandler(FileDownloaded);
wc.DownloadProgressChanged += new DownloadProgressChangedEventHandler(FileDownloadProgress);
chckAutorun.Checked = Properties.Settings.Default.autorun;
checkConnection();
if(!checkVersion())
downloadClient();
else
{
pbDownload.Value = 100;
btnPlay.Enabled = true;
lblProgress.Text = "updated";
if (chckAutorun.Checked)
btnPlay.PerformClick();
}
}
private bool checkConnection()
{
verifyUri = new Uri("http://" + verifySite);
downloadUri = new Uri("http://" + downloadSite);
WebRequest req = WebRequest.Create(verifyUri);
try
{
HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
return true;
}
catch { }
verifyUri = new Uri("https://" + verifySite);
downloadUri = new Uri("https://" + downloadUri);
req = WebRequest.Create(verifyUri);
try
{
HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
return true;
}
catch { }
return false;
}
private void downloadClient()
{
try
{
wc.DownloadFileAsync(downloadUri, Path.Combine(downloadPath, clientName));
}
catch { }
}
private bool checkVersion()
{
lblProgress.Text = "checking for updates";
try
{
currVer = FileVersionInfo.GetVersionInfo(Path.Combine(downloadPath, clientName)).FileVersion;
}
catch {
currVer = "";
}
try
{
userVer = wc.DownloadString(verifyUri);
}
catch {
userVer = "";
}
return currVer == userVer && currVer != "";
}
private void FileDownloaded(object sender, AsyncCompletedEventArgs e)
{
btnPlay.Enabled = true;
lblProgress.Text = "updated";
if (chckAutorun.Checked)
btnPlay.PerformClick();
}
private void FileDownloadProgress(object sender, DownloadProgressChangedEventArgs e)
{
long received = e.BytesReceived / 1000;
long toReceive = e.TotalBytesToReceive / 1000;
lblProgress.Text = string.Format("{0}KB {1}/ {2}KB", received, Repeat(" ", Math.Abs(-5 + Math.Min(5, received.ToString().Length))*2), toReceive);
pbDownload.Value = e.ProgressPercentage;
}
private void btnPlay_Click(object sender, EventArgs e)
{
btnPlay.Enabled = false;
if(checkVersion())
{
lblProgress.Text = "Starting...";
Process.Start(Path.Combine(downloadPath, clientName));
this.Close();
}
else
{
downloadClient();
}
}
public static string Repeat(string instr, int n)
{
if (string.IsNullOrEmpty(instr))
return instr;
var result = new StringBuilder(instr.Length * n);
return result.Insert(0, instr, n).ToString();
}
private void chckAutorun_CheckedChanged(object sender, EventArgs e)
{
Properties.Settings.Default.autorun = chckAutorun.Checked;
Properties.Settings.Default.Save();
}`
I've managed to achieve what I need by enabling autoindex on web server and download string of files in folder ending with .map .
string mapSite = wc.DownloadString(new Uri("http://" + mapsSite));
maps = Regex.Matches(mapSite, "<a href=\"(.*).map\">");
foreach (Match m in maps)
{
string mapName = m.Value.Remove(0, 9).Remove(m.Length - 11);
downloaded = false;
wc.DownloadFileAsync(new Uri("http://" + mapsSite + mapName), Path.Combine(downloadPath, #"mapFolder/" + mapName));
while (!downloaded) { }
}
So, I set up a file browser, fully working.
But now I want to take the end location where you went and put that location into a TextBox. Which can still be typed in by the user for if they want to manually type the file location.
private void button1_Click(object sender, EventArgs e)
{
int size = -1;
DialogResult result = openFileDialog1.ShowDialog();
if (result == DialogResult.OK)
{
string file = openFileDialog1.FileName;
try
{
string text = File.ReadAllText(file);
size = text.Length;
}
catch (IOException) { }
}
Console.WriteLine(size);
Console.WriteLine(result);
}
You can get the full path
textBox1.Text = file;
and the last folder name
string lastFolderName = Path.GetFileName(Path.GetDirectoryName(file));
textBox1.Text = lastFolderName;
in your code you can use like below, if you want to use the location from another scope then make file variable global
string file = "";
private void button1_Click(object sender, EventArgs e)
{
int size = -1;
DialogResult result = openFileDialog1.ShowDialog();
if (result == DialogResult.OK)
{
file = openFileDialog1.FileName;
try
{
string text = File.ReadAllText(file);
size = text.Length;
textBox1.Text = file; // for full location
textBox2.Text = Path.GetFileName(Path.GetDirectoryName(file)); // for last folder name
}
catch (IOException)
{
}
}
}
and then
private void textBox1_TextChanged(object sender, EventArgs e)
{
textBox2.Text = file;
}
Can I use a declared variable or a instance of an object from one method to another?
private void OnBrowseFileClick(object sender, RoutedEventArgs e)
{
string path = null;
path = OpenFile();
}
private string OpenFile()
{
string path = null;
OpenFileDialog fileDialog = new OpenFileDialog();
fileDialog.Title = "Open source file";
fileDialog.InitialDirectory = "c:\\";
fileDialog.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*";
fileDialog.FilterIndex = 2;
fileDialog.RestoreDirectory = true;
Nullable<bool> result = fileDialog.ShowDialog();
if (result == true)
{
path = fileDialog.FileName;
}
textBox1.Text = path;
return path;
}
Now, I want to get that path and write it on excel. how will I do this, please help, I am week old in using C#.
private void btnCreateReport_Click(object sender, RoutedEventArgs e)
{
string filename = "sample.xls"; //Dummy Data
string functionName = "functionName"; //Dummy Data
string path = null;
AnalyzerCore.ViewModel.ReportGeneratorVM reportGeneratorVM = new AnalyzerCore.ViewModel.ReportGeneratorVM();
reportGeneratorVM.ReportGenerator(filename, functionName, path);
}
Thanks
Use an instance field to store the value of your variable.
Like so:
public class MyClass
{
// New instance field
private string _path = null;
private void OnBrowseFileClick(object sender, RoutedEventArgs e)
{
// Notice the use of the instance field
_path = OpenFile();
}
// OpenFile implementation here...
private void btnCreateReport_Click(object sender, RoutedEventArgs e)
{
string filename = "st_NodataSet.xls"; //Dummy Data
string functionName = "functionName"; //Dummy Data
AnalyzerCore.ViewModel.ReportGeneratorVM reportGeneratorVM = new AnalyzerCore.ViewModel.ReportGeneratorVM();
// Reuse the instance field here
reportGeneratorVM.ReportGenerator(filename, functionName, _path);
}
}
Here is a link which describes fields in much more detail than what I could.
Move the string path as a member inside your class, and remove the declaration inside the methods. that should do it
Use string path as a class level variable.
Use static private string path if you want to use it between pages.
Use private string path if you only need to use it on the current page.
you must define the variable as field in your class:
Private string path = null;
use static private string path;