Strange problem when not in debugger

R

Rinaldo

Hi,

When I start my program in the debugger, there is no problem, but when not I
get an exception.

It appears in:

private void Upload(string filename, string FTnaam)
{
MessageBox.Show("in upload.");
FileInfo fileInf = new FileInfo(filename);
MessageBox.Show("file: " + filename + " upload: " + FTnaam);

string uri = "ftp://" + F1.FTPserver + FTnaam; // fileInf.Name;
FtpWebRequest reqFTP;
MessageBox.Show("Uri :" + uri);

// Create FtpWebRequest object from the Uri provided
-> reqFTP = (FtpWebRequest) FtpWebRequest.Create(new Uri("ftp://"
+ F1.FTPserver + FTnaam));
here its going wrong
 
R

Rinaldo

Hi Peter,

The error is: The type-initialisation function for System.Uri has made an
exception

private void Upload(string filename, string FTnaam) // filename
@"c:\'map\somefile.pdf FTnaam /backup/map/somefile.pdf
{
FileInfo fileInf = new FileInfo(filename);

string uri = "ftp://" + F1.FTPserver + FTnaam; //
ftp:///ftp.someserver.nl/backup/map/somefile.pdf
FtpWebRequest reqFTP;

// Create FtpWebRequest object from the Uri provided
reqFTP = (FtpWebRequest) FtpWebRequest.Create(new Uri("ftp://" +
F1.FTPserver + FTnaam)); // error

The maps are already created by another routine that is working.
 
R

Rinaldo

The translated text is from dutch and I can't chage it easaly because my
whole system is dutch.

I've tryed
reqFTP = (FtpWebRequest)FtpWebRequest.Create(new
Uri("ftp://ftp.lampiesoft.nl" + FTnaam));
where FTnaam = /backup/map/file.pdf

I've removed FTnaam, but the same error appears.

The strange thing is, while debugging in debugger there is no error.
 
F

Family Tree Mike

Two and a half questions:

Are you positive the code returns the same string for F1.FTPServer in all
cases?

Are you running the debug version from outside Visual Studio, or the release
version? Are you sure the external version timestamp and the source code
time stamps match?
 
R

Rinaldo

Positive that the string return the same value. Even when I hardcode the URL
+ path without calling any variable I get the same error.

I running a debug version outside visual studio,yes.

The timestamps are correct, The exe is newer than the .cs files ( a few
minutes).
 
R

Rinaldo

Peter Duniho said:
The bottom line: until you post a concise-but-complete code example that
reliably reproduces the problem, you're unlikely to get an actual answer.

Must I post it here or somewhere else?
 
R

Rinaldo

Here it goes:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Net;
using Microsoft;

namespace WebBackup
{
public partial class frmBackup : Form
{
private string huidigWeb;
private string huidigMap;

private WebBackupForm f1 = new WebBackupForm();

public frmBackup(WebBackupForm F1)
{
f1 = F1;
InitializeComponent();
}

public WebBackupForm F1
{
get { return f1; }
}

/// <summary>
/// Method to upload the specified file to the specified FTP Server
/// </summary>
/// <param name="filename">file full name to be uploaded</param>
///
/// filename = local
/// FTnaam = FTP naam
private void Upload(string filename, string FTnaam)
{
// MessageBox.Show("in upload.");
FileInfo fileInf = new FileInfo(filename);
// MessageBox.Show("file: " + filename + " upload: "
+ FTnaam);

string uri = "ftp://" + F1.FTPserver + "/"; // fileInf.Name;
FtpWebRequest reqFTP;
MessageBox.Show("Uri :" + uri);

// Create FtpWebRequest object from the Uri provided

reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(uri));
//"ftp://" + F1.FTPserver + "/" + FTnaam));

// MessageBox.Show("ReqFTP");
//fileInf.Name));
MessageBox.Show("After uri");

// Provide the WebPermission Credintials
reqFTP.Credentials = new NetworkCredential(F1.FTPnaam,
F1.FTPpassword);

// By default KeepAlive is true, where the control connection is
not closed
// after a command is executed.
reqFTP.KeepAlive = false;

// Specify the command to be executed.
reqFTP.Method = WebRequestMethods.Ftp.UploadFile;

// Specify the data transfer type.
reqFTP.UseBinary = true;

// Notify the server about the size of the uploaded file
reqFTP.ContentLength = fileInf.Length;

// Calculate the progressbar

long len = fileInf.Length;
len = len / 2048;
if (len > 0)
len = 1000 / len;
else len = 1;
if (len <= 0)
len = 1;

int max = (int)len;

// Show count

long Teller = fileInf.Length;
lblTeller.Text = Teller.ToString();

// The buffer size is set to 2kb
int buffLength = 2048;
byte[] buff = new byte[buffLength];
int contentLen;

// Opens a file stream (System.IO.FileStream) to read the file
to be uploaded
FileStream fs = fileInf.OpenRead();
this.lblBestand.Text = FTnaam;

// try
// {
// Stream to which the file to be upload is written
Stream strm = reqFTP.GetRequestStream();

// Read from the file stream 2kb at a time
contentLen = fs.Read(buff, 0, buffLength);

// Till Stream content ends
while (contentLen != 0)
{
// Write Content from the file stream to the FTP Upload
Stream
strm.Write(buff, 0, contentLen);
contentLen = fs.Read(buff, 0, buffLength);
progressBar.Value = (int)len;
progressBar.PerformStep();
len += max;
if (len >= 1000) len = 0;
Teller -= (long)contentLen;
lblTeller.Text = Teller.ToString();
this.Refresh();
}

// Close the file stream and the Request Stream
strm.Close();
fs.Close();
}

public void DeleteFTP
(string
fileName)
{
try
{
string uri = "ftp://" + F1.FTPserver + "/" + fileName;
FtpWebRequest reqFTP;
reqFTP = (FtpWebRequest)FtpWebRequest.Create(new
Uri("ftp://" + F1.FTPserver + "/" + fileName));

reqFTP.Credentials = new NetworkCredential(F1.FTPnaam,
F1.FTPpassword);
reqFTP.KeepAlive = false;
reqFTP.Method = WebRequestMethods.Ftp.DeleteFile;

string result = String.Empty;
FtpWebResponse response =
(FtpWebResponse)reqFTP.GetResponse();
long size = response.ContentLength;
Stream datastream = response.GetResponseStream();
StreamReader sr = new StreamReader(datastream);
result = sr.ReadToEnd();
sr.Close();
datastream.Close();
response.Close();
}
catch (Exception ex)
{
// MessageBox.Show(ex.Message, "FTP 2.0
Delete");
}
}

private
void makedir
(string
dirName)
{
/* string dir = dirName.Replace('/', '\\');
dir = "H:\\" + dir;
Directory.CreateDirectory(dir);

return;
*/
// MessageBox.Show("In makedir.");
FtpWebRequest reqFTP;
try
{
// dirName = name of the directory to create.
reqFTP = (FtpWebRequest)FtpWebRequest.Create(new
Uri("ftp://" + F1.FTPserver + "/" + dirName));
reqFTP.Method = WebRequestMethods.Ftp.MakeDirectory;
reqFTP.UseBinary = true;
reqFTP.Credentials = new NetworkCredential(F1.FTPnaam,
F1.FTPpassword);
FtpWebResponse response =
(FtpWebResponse)reqFTP.GetResponse();
Stream ftpStream = response.GetResponseStream();

ftpStream.Close();
response.Close();
}
catch (Exception ex)
{
// MessageBox.Show(ex.Message, " Directory fout");
}
}

private
void btnAnnuleer_Click
(object
sender,
EventArgs e)
{
this.Close();
}

private
void btnStart_Click
(object
sender,
EventArgs e)
{
int i;
int Positie = 0;
string Mappen = "";
string WebMappen = "";
string backup = "/backup/";

lblBackup.Text = "Bezig met de backup naar " + F1.FTPserver;
this.Refresh();
DeleteFTP("backup/");
// makedir(backup);

// Ga dooe de lijst heen van mappen die door de gebruiker
aangeklikt zijn om te
// backuppen

for (i = 0; i < F1.BestandsLijst.Items.Count; i++)
{
Mappen = F1.BestandsLijst.Items.ToString();
Positie = Mappen.IndexOf('\\');
WebMappen = backup;

WebMappen += Mappen.Substring(Positie + 1);
WebMappen = WebMappen.Replace('\\', '/');
string dirHulp = "";

// Maak eerst de mappen die niet met bestanden moetn worden
gechreven
foreach (string dirPart in WebMappen.Split('/'))
{
dirHulp += dirPart;
dirHulp += "/";
if (dirHulp.Length > 1)
{
makedir(dirHulp);
}
}

DirectoryInfo dirinf = new DirectoryInfo(Mappen);
huidigWeb = dirHulp;
huidigMap = Mappen;

schrijfNaarWeb(Mappen);
// string[] bestanden = GetFileList();
}
lblBestand.Text = "Klaar met uploaden.";
this.Refresh();
}

public
void schrijfNaarWeb
(string
directory)
{
if (!Directory.Exists(directory))
{
throw new FileNotFoundException("De map bestaat niet. " +
directory);
}

try
{
string[] files = Directory.GetFiles(directory);

foreach (string file in files)
{
if (file != null)
{
string copyfrom = file;
string copyto;
string webfile = file.Replace('\\', '/');
int wfpos = webfile.IndexOf('/');
webfile = "/backup/" + webfile.Substring(wfpos + 1);
copyto = webfile.Replace('/', '\\');
copyto = "H:\\" + copyto;
lblBackup.Text = copyfrom;
this.Refresh();
// File.Copy(copyfrom, copyto);
Upload(file, webfile);
}
}

string[] dirs = Directory.GetDirectories(directory);

foreach (string dir in dirs)
{
string webdir = dir.Replace('\\', '/');
int wdpos = webdir.IndexOf('/');
webdir = "/backup/" + webdir.Substring(wdpos + 1);
makedir(webdir);

schrijfNaarWeb(dir);
}
}
catch (Exception ex)
{
MessageBox.Show("Exeception :" + ex.Message);
}
}

}
}
 
R

Rinaldo

2e part, sorry it was midnight here.

using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Net;

namespace WebBackup
{
public partial class frmDownload : Form
{
private WebBackupForm f1 = new WebBackupForm();
private string Station = "";

public frmDownload(WebBackupForm F1)
{
f1 = F1;
InitializeComponent();
}

public WebBackupForm F1
{
get { return f1; }
}

private string[] GetFilesDetailList()
{
string[] downloadFiles;
try
{
StringBuilder result = new StringBuilder();
FtpWebRequest ftp;
ftp = (FtpWebRequest)FtpWebRequest.Create(new Uri("ftp://" +
F1.FTPserver + "/backup"));
ftp.Credentials = new NetworkCredential(F1.FTPnaam,
F1.FTPpassword);
ftp.Method = WebRequestMethods.Ftp.ListDirectoryDetails;
WebResponse response = ftp.GetResponse();
StreamReader reader = new
StreamReader(response.GetResponseStream());
string line = reader.ReadLine();
while (line != null)
{
result.Append(line);
result.Append("\n");
line = reader.ReadLine();
}

result.Remove(result.ToString().LastIndexOf("\n"), 1);
reader.Close();
response.Close();
return result.ToString().Split('\n');
//MessageBox.Show(result.ToString().Split('\n'));
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
downloadFiles = null;
return downloadFiles;
}
}

public string[] GetFileList()
{
string[] downloadFiles;
StringBuilder result = new StringBuilder();
FtpWebRequest reqFTP;
try
{
reqFTP = (FtpWebRequest)FtpWebRequest.Create(new
Uri("ftp://" + F1.FTPserver + "/backup"));
reqFTP.UseBinary = true;
reqFTP.Credentials = new NetworkCredential(F1.FTPnaam,
F1.FTPpassword);
reqFTP.Method = WebRequestMethods.Ftp.ListDirectory;
WebResponse response = reqFTP.GetResponse();
StreamReader reader = new
StreamReader(response.GetResponseStream());
//MessageBox.Show(reader.ReadToEnd());
string line = reader.ReadLine();
while (line != null)
{
result.Append(line);
result.Append("\n");
line = reader.ReadLine();
}
result.Remove(result.ToString().LastIndexOf('\n'), 1);
reader.Close();
response.Close();
//MessageBox.Show(response.StatusDescription);
return result.ToString().Split('\n');
}
catch (Exception ex)
{
System.Windows.Forms.MessageBox.Show(ex.Message);
downloadFiles = null;
return downloadFiles;
}
}

private void Download(string filePath, string fileName)
{
FtpWebRequest reqFTP;
try
{
//filePath = <<The full path where the file is to be
created.>>,
//fileName = <<Name of the file to be created(Need not be
the name of the file on FTP server).>>
FileStream outputStream = new FileStream(filePath + "\\" +
fileName, FileMode.Create);

reqFTP = (FtpWebRequest)FtpWebRequest.Create(new
Uri("ftp://" + F1.FTPserver + "/" + fileName));
reqFTP.Method = WebRequestMethods.Ftp.DownloadFile;
reqFTP.UseBinary = true;
reqFTP.Credentials = new NetworkCredential(F1.FTPnaam,
F1.FTPpassword);
FtpWebResponse response =
(FtpWebResponse)reqFTP.GetResponse();
Stream ftpStream = response.GetResponseStream();
long cl = response.ContentLength;
int bufferSize = 2048;
int readCount;
byte[] buffer = new byte[bufferSize];

readCount = ftpStream.Read(buffer, 0, bufferSize);
while (readCount > 0)
{
outputStream.Write(buffer, 0, readCount);
readCount = ftpStream.Read(buffer, 0, bufferSize);
}

ftpStream.Close();
outputStream.Close();
response.Close();
}
catch (Exception ex)
{
// MessageBox.Show(ex.Message);
}
}

private void btnHerstellen_Click(object sender, EventArgs e)
{
Station = txtboxDrive.Text + ":\\";
if (Station.Length > 3)
{
MessageBox.Show("Illegaal Station");
return;
}

string[] Directorys = GetFilesDetailList();

}

}
}
 
R

Rinaldo

3e part

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;

namespace WebBackup
{
public partial class WebBackupForm : Form
{
private static string driveLetter = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
private DirectoryInfo folder = null;
public string configBestand = "WebBackup.config";
public string binBestand = "Binaries.config";
public StreamReader WebBackupReader;
public StreamWriter WebBackupWriter;
public BinaryWriter bWebBackupWriter;
public BinaryReader bWebBackupReader;
public TextWriter tWebBackupWriter;
public TextReader tWebBackupReader;
public string FTPpassword = "";
public string FTPnaam = "";
public string FTPserver = "";

public WebBackupForm()
{

InitializeComponent();

FillTree();
}

private void FillTree()
{
DirectoryInfo directory;
string Pad = "";
treeView.Nodes.Clear();

foreach (char c in driveLetter)
{
Pad = c + ":\\";
try
{
directory = new DirectoryInfo(Pad);
if (directory.Exists == true)
{
TreeNode newNode = new TreeNode(directory.FullName);
treeView.Nodes.Add(newNode);
getSubDirs(newNode);

}
}
catch (Exception bericht)
{
MessageBox.Show("Fout in verkrijgen hoofdmappen: " +
bericht);
}
}

}

private void getSubDirs (TreeNode parent)
{
DirectoryInfo directory;
try
{
// Als we de map niet al bekeken hebben.

if (parent.Nodes.Count == 0)
{
directory = new DirectoryInfo(parent.FullPath);
foreach (DirectoryInfo dir in
directory.GetDirectories())
{
TreeNode newNode = new TreeNode(dir.Name);
parent.Nodes.Add(newNode);
}
}

foreach (TreeNode node in parent.Nodes)
{
if (node.Nodes.Count == 0)
{
directory = new DirectoryInfo(node.FullPath);

foreach (DirectoryInfo dir in
directory.GetDirectories())
{
TreeNode newNode = new TreeNode(dir.Name);
node.Nodes.Add(newNode);
}
}
}
}
catch (Exception bericht)
{
Console.WriteLine("Fout in het verkrijgen van de
subdirectory's: " + bericht);
// MessageBox.Show("Fout in het verkrijgen van de
subdirectory's: " + bericht);
}
}

private void treeView_BeforeExpand(object sender,
TreeViewCancelEventArgs e)
{
getSubDirs(e.Node);

folder = new DirectoryInfo(e.Node.FullPath);

}

private void treeView_BeforeSelect(object sender,
TreeViewCancelEventArgs e)
{
getSubDirs(e.Node);

folder = new DirectoryInfo(e.Node.FullPath);
}

private void Toevogen_Click(object sender, EventArgs e)
{
string Pad = "";

if (folder == null)
return;
else
Pad = folder.FullName;


if (String.IsNullOrEmpty(Pad) == true) return;
if (BestandsLijst.Items.Count < 0) return;

if (BestandsLijst.Items.Contains(Pad) == false)
{
BestandsLijst.Items.Add(Pad);
}
}

private void bewaarInstelling_Click(object sender, EventArgs e)
{
WebBackupWriter = new StreamWriter(configBestand,false);
WebBackupWriter.Write(ftpPassword.Text +Environment.NewLine);
WebBackupWriter.Write(ftpServerIP.Text + Environment.NewLine);
WebBackupWriter.Write(ftpUserID.Text + Environment.NewLine);

for (int i = 0; i < BestandsLijst.Items.Count; i++ )
WebBackupWriter.Write(BestandsLijst.Items.ToString() +
Environment.NewLine);
WebBackupWriter.Close();

if (File.Exists(binBestand))
File.Delete(binBestand);

bWebBackupWriter = new BinaryWriter (File.Open( binBestand,
FileMode.Create));

bWebBackupWriter.Write(chkZondag.Checked);
bWebBackupWriter.Write(chkMaandag.Checked);
bWebBackupWriter.Write(chkDinsdag.Checked);
bWebBackupWriter.Write(chkWoensdag.Checked);
bWebBackupWriter.Write(chkDonderdag.Checked);
bWebBackupWriter.Write(chkVrijdag.Checked);
bWebBackupWriter.Write(chkZaterdag.Checked);

// long tijd = dateTimePicker

bWebBackupWriter.Close();
}

private void WebBackupForm_Load(object sender, EventArgs e)
{
if (File.Exists(configBestand) && File.Exists(binBestand))
{
WebBackupReader = new StreamReader(configBestand);

ftpPassword.Text = WebBackupReader.ReadLine();
ftpServerIP.Text = WebBackupReader.ReadLine();
ftpUserID.Text = WebBackupReader.ReadLine();
string str = null;
while ((str = WebBackupReader.ReadLine())!= null)
{
BestandsLijst.Items.Add(str);
}

WebBackupReader.Close();

bWebBackupReader = new BinaryReader(File.Open( binBestand,
FileMode.Open));
chkZondag.Checked = bWebBackupReader.ReadBoolean();
chkMaandag.Checked = bWebBackupReader.ReadBoolean();
chkDinsdag.Checked = bWebBackupReader.ReadBoolean();
chkWoensdag.Checked = bWebBackupReader.ReadBoolean();
chkDonderdag.Checked = bWebBackupReader.ReadBoolean();
chkVrijdag.Checked = bWebBackupReader.ReadBoolean();
chkZaterdag.Checked = bWebBackupReader.ReadBoolean();

bWebBackupReader.Close();
FTPserver = ftpServerIP.Text;
FTPpassword = ftpPassword.Text;
FTPnaam = ftpUserID.Text;
}
}

private void btnVerwijderen_Click(object sender, EventArgs e)
{
int i = BestandsLijst.SelectedIndex;
if (i <0)
return;

BestandsLijst.Items.RemoveAt(i);
BestandsLijst.Refresh();

}

private void maakBackup_Click(object sender, EventArgs e)
{
if (BestandsLijst.Items.Count <= 0)
{
MessageBox.Show("Geen mappen geselecteerd om te backuppen.",
"Informatie",MessageBoxButtons.OK, MessageBoxIcon.Information);
return;
}

FTPserver = ftpServerIP.Text;
FTPpassword = ftpPassword.Text;
FTPnaam = ftpUserID.Text;

if ((String.IsNullOrEmpty(FTPserver)==true) ||
(String.IsNullOrEmpty(FTPpassword)== true)||
(String.IsNullOrEmpty(FTPnaam))==true)
{
MessageBox.Show("Geen gegevens voor Servernaam of
Serverpaswoord of Inlognaam", "Informatie",
MessageBoxButtons.OK,
MessageBoxIcon.Information);
return;
}
frmBackup upload = new frmBackup(this);
upload.ShowDialog();
}

private void button1_Click(object sender, EventArgs e)
{
AboutBox Over = new AboutBox();
Over.Show();
}

private void WebBackupForm_Activated(object sender, EventArgs e)
{
}

private void button2_Click(object sender, EventArgs e)
{
frmDownload herstel = new frmDownload(this);
herstel.ShowDialog();
}
}

}
 
R

Rinaldo

4e part about

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Windows.Forms;
using System.Reflection;

namespace WebBackup
{
partial class AboutBox : Form
{
public AboutBox()
{
InitializeComponent();

// Initialize the AboutBox to display the product information
from the assembly information.
// Change assembly information settings for your application
through either:
// - Project->Properties->Application->Assembly Information
// - AssemblyInfo.cs
this.Text = String.Format("Over {0}", AssemblyTitle);
this.labelProductName.Text = AssemblyProduct;
this.labelVersion.Text = String.Format("Version {0}",
AssemblyVersion);
this.labelCopyright.Text = AssemblyCopyright;
this.labelCompanyName.Text = AssemblyCompany;
this.textBoxDescription.Text = AssemblyDescription;
}

#region Assembly Attribute Accessors

public string AssemblyTitle
{
get
{
// Get all Title attributes on this assembly
object[] attributes =
Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(AssemblyTitleAttribute),
false);
// If there is at least one Title attribute
if (attributes.Length > 0)
{
// Select the first one
AssemblyTitleAttribute titleAttribute =
(AssemblyTitleAttribute)attributes[0];
// If it is not an empty string, return it
if (titleAttribute.Title != "")
return titleAttribute.Title;
}
// If there was no Title attribute, or if the Title
attribute was the empty string, return the .exe name
return
System.IO.Path.GetFileNameWithoutExtension(Assembly.GetExecutingAssembly().CodeBase);
}
}

public string AssemblyVersion
{
get
{
return
Assembly.GetExecutingAssembly().GetName().Version.ToString();
}
}

public string AssemblyDescription
{
get
{
// Get all Description attributes on this assembly
object[] attributes =
Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(AssemblyDescriptionAttribute),
false);
// If there aren't any Description attributes, return an
empty string
if (attributes.Length == 0)
return "";
// If there is a Description attribute, return its value
return
((AssemblyDescriptionAttribute)attributes[0]).Description;
}
}

public string AssemblyProduct
{
get
{
// Get all Product attributes on this assembly
object[] attributes =
Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(AssemblyProductAttribute),
false);
// If there aren't any Product attributes, return an empty
string
if (attributes.Length == 0)
return "";
// If there is a Product attribute, return its value
return ((AssemblyProductAttribute)attributes[0]).Product;
}
}

public string AssemblyCopyright
{
get
{
// Get all Copyright attributes on this assembly
object[] attributes =
Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(AssemblyCopyrightAttribute),
false);
// If there aren't any Copyright attributes, return an empty
string
if (attributes.Length == 0)
return "";
// If there is a Copyright attribute, return its value
return
((AssemblyCopyrightAttribute)attributes[0]).Copyright;
}
}

public string AssemblyCompany
{
get
{
// Get all Company attributes on this assembly
object[] attributes =
Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(AssemblyCompanyAttribute),
false);
// If there aren't any Company attributes, return an empty
string
if (attributes.Length == 0)
return "";
// If there is a Company attribute, return its value
return ((AssemblyCompanyAttribute)attributes[0]).Company;
}
}
#endregion

private void okButton_Click(object sender, EventArgs e)
{
this.Close();
}
}
}
 
R

Rinaldo

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Net;
using Microsoft;

namespace WebBackup
{
public partial class frmBackup : Form
{
private string huidigWeb;
private string huidigMap;

private WebBackupForm f1 = new WebBackupForm();

public frmBackup(WebBackupForm F1)
{
f1 = F1;
InitializeComponent();
}

public WebBackupForm F1
{
get { return f1; }
}

/// <summary>
/// Method to upload the specified file to the specified FTP Server
/// </summary>
/// <param name="filename">file full name to be uploaded</param>
///
/// filename = local
/// FTnaam = FTP naam
private void Upload(string filename, string FTnaam)
{
// MessageBox.Show("in upload.");
FileInfo fileInf = new FileInfo(filename);
// MessageBox.Show("file: " + filename + " upload: "
+ FTnaam);

string uri = "ftp://" + F1.FTPserver + "/"; // fileInf.Name;
FtpWebRequest reqFTP;
MessageBox.Show("Uri :" + uri);

// Create FtpWebRequest object from the Uri provided

reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(uri));
//"ftp://" + F1.FTPserver + "/" + FTnaam));

// MessageBox.Show("ReqFTP");
//fileInf.Name));
MessageBox.Show("After uri");

// Provide the WebPermission Credintials
reqFTP.Credentials = new NetworkCredential(F1.FTPnaam,
F1.FTPpassword);

// By default KeepAlive is true, where the control connection is
not closed
// after a command is executed.
reqFTP.KeepAlive = false;

// Specify the command to be executed.
reqFTP.Method = WebRequestMethods.Ftp.UploadFile;

// Specify the data transfer type.
reqFTP.UseBinary = true;

// Notify the server about the size of the uploaded file
reqFTP.ContentLength = fileInf.Length;

// Calculate the progressbar

long len = fileInf.Length;
len = len / 2048;
if (len > 0)
len = 1000 / len;
else len = 1;
if (len <= 0)
len = 1;

int max = (int)len;

// Show count

long Teller = fileInf.Length;
lblTeller.Text = Teller.ToString();

// The buffer size is set to 2kb
int buffLength = 2048;
byte[] buff = new byte[buffLength];
int contentLen;

// Opens a file stream (System.IO.FileStream) to read the file
to be uploaded
FileStream fs = fileInf.OpenRead();
this.lblBestand.Text = FTnaam;

// try
// {
// Stream to which the file to be upload is written
Stream strm = reqFTP.GetRequestStream();

// Read from the file stream 2kb at a time
contentLen = fs.Read(buff, 0, buffLength);

// Till Stream content ends
while (contentLen != 0)
{
// Write Content from the file stream to the FTP Upload
Stream
strm.Write(buff, 0, contentLen);
contentLen = fs.Read(buff, 0, buffLength);
progressBar.Value = (int)len;
progressBar.PerformStep();
len += max;
if (len >= 1000) len = 0;
Teller -= (long)contentLen;
lblTeller.Text = Teller.ToString();
this.Refresh();
}

// Close the file stream and the Request Stream
strm.Close();
fs.Close();
}

public void DeleteFTP
(string
fileName)
{
try
{
string uri = "ftp://" + F1.FTPserver + "/" + fileName;
FtpWebRequest reqFTP;
reqFTP = (FtpWebRequest)FtpWebRequest.Create(new
Uri("ftp://" + F1.FTPserver + "/" + fileName));

reqFTP.Credentials = new NetworkCredential(F1.FTPnaam,
F1.FTPpassword);
reqFTP.KeepAlive = false;
reqFTP.Method = WebRequestMethods.Ftp.DeleteFile;

string result = String.Empty;
FtpWebResponse response =
(FtpWebResponse)reqFTP.GetResponse();
long size = response.ContentLength;
Stream datastream = response.GetResponseStream();
StreamReader sr = new StreamReader(datastream);
result = sr.ReadToEnd();
sr.Close();
datastream.Close();
response.Close();
}
catch (Exception ex)
{
// MessageBox.Show(ex.Message, "FTP 2.0
Delete");
}
}

private
void makedir
(string
dirName)
{
/* string dir = dirName.Replace('/', '\\');
dir = "H:\\" + dir;
Directory.CreateDirectory(dir);

return;
*/
// MessageBox.Show("In makedir.");
FtpWebRequest reqFTP;
try
{
// dirName = name of the directory to create.
reqFTP = (FtpWebRequest)FtpWebRequest.Create(new
Uri("ftp://" + F1.FTPserver + "/" + dirName));
reqFTP.Method = WebRequestMethods.Ftp.MakeDirectory;
reqFTP.UseBinary = true;
reqFTP.Credentials = new NetworkCredential(F1.FTPnaam,
F1.FTPpassword);
FtpWebResponse response =
(FtpWebResponse)reqFTP.GetResponse();
Stream ftpStream = response.GetResponseStream();

ftpStream.Close();
response.Close();
}
catch (Exception ex)
{
// MessageBox.Show(ex.Message, " Directory fout");
}
}

private
void btnAnnuleer_Click
(object
sender,
EventArgs e)
{
this.Close();
}

private
void btnStart_Click
(object
sender,
EventArgs e)
{
int i;
int Positie = 0;
string Mappen = "";
string WebMappen = "";
string backup = "/backup/";

lblBackup.Text = "Bezig met de backup naar " + F1.FTPserver;
this.Refresh();
DeleteFTP("backup/");
// makedir(backup);

// Ga dooe de lijst heen van mappen die door de gebruiker
aangeklikt zijn om te
// backuppen

for (i = 0; i < F1.BestandsLijst.Items.Count; i++)
{
Mappen = F1.BestandsLijst.Items.ToString();
Positie = Mappen.IndexOf('\\');
WebMappen = backup;

WebMappen += Mappen.Substring(Positie + 1);
WebMappen = WebMappen.Replace('\\', '/');
string dirHulp = "";

// Maak eerst de mappen die niet met bestanden moetn worden
gechreven
foreach (string dirPart in WebMappen.Split('/'))
{
dirHulp += dirPart;
dirHulp += "/";
if (dirHulp.Length > 1)
{
makedir(dirHulp);
}
}

DirectoryInfo dirinf = new DirectoryInfo(Mappen);
huidigWeb = dirHulp;
huidigMap = Mappen;

schrijfNaarWeb(Mappen);
// string[] bestanden = GetFileList();
}
lblBestand.Text = "Klaar met uploaden.";
this.Refresh();
}

public
void schrijfNaarWeb
(string
directory)
{
if (!Directory.Exists(directory))
{
throw new FileNotFoundException("De map bestaat niet. " +
directory);
}

try
{
string[] files = Directory.GetFiles(directory);

foreach (string file in files)
{
if (file != null)
{
string copyfrom = file;
string copyto;
string webfile = file.Replace('\\', '/');
int wfpos = webfile.IndexOf('/');
webfile = "/backup/" + webfile.Substring(wfpos + 1);
copyto = webfile.Replace('/', '\\');
copyto = "H:\\" + copyto;
lblBackup.Text = copyfrom;
this.Refresh();
// File.Copy(copyfrom, copyto);
Upload(file, webfile);
}
}

string[] dirs = Directory.GetDirectories(directory);

foreach (string dir in dirs)
{
string webdir = dir.Replace('\\', '/');
int wdpos = webdir.IndexOf('/');
webdir = "/backup/" + webdir.Substring(wdpos + 1);
makedir(webdir);

schrijfNaarWeb(dir);
}
}
catch (Exception ex)
{
MessageBox.Show("Exeception :" + ex.Message);
}
}

}
}
 
R

Rinaldo

Ihope that it was all. If missing something, I hear it. The program's that I
make are free for charge. It is a hobby of my. In the past, 20 years ago, I
programmed C, but gorget all about it.
 
R

Rinaldo

How small it must be? I thought you mean the whole code. The first message
is with the code wich goes wrong. Pfff I read the message with a dictionary
with me.

Here it goes wrong in the code:

private void Upload(string filename, string FTnaam)
{
// MessageBox.Show("in upload.");
FileInfo fileInf = new FileInfo(filename);
// MessageBox.Show("file: " + filename + " upload: "
+ FTnaam);

string uri = "ftp://" + F1.FTPserver + "/"; //
ftp://ftp.lampiesoft.nl goes also wrong as uri
FtpWebRequest reqFTP;
MessageBox.Show("Uri :" + uri);

// Create FtpWebRequest object from the Uri provided

reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(uri));
//"ftp://" + F1.FTPserver + "/" + FTnaam));

with the call to new Uri(uri)

I thought the whole code mabe someone can reproduce it.

I think some english/american sentences I do not understand correctly, I try
it but there are nu C# groups in dutch where I can ask.

Sorry for the unconvinience.

Rinaldo
 
R

Rinaldo

Thank you Pete for explanation. I now know the problem. Anyway anyhow VS
doesn't clean up the bin directory or whatsoever.
I had deleted the bin folder and try again. Someway somehow it worked again
(the program) This was pure luck I did it because I had enough of it.
I now understand that a small amount of code posted here must be enough for
example.

I hope that someone can make use of my (lucky) deletion for someone with the
same error, however I think it is not happend very much.
I shal remember the things you told me.

Again, thanks for the support, because it is hard to seek an error in
someone els its code.

Rinaldo
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top