|
i have a program that show the size of programs but i want something to add to the program but i have no idea so if the program gives the access denied error it stops and i don't want that it stops and it does the next file how and where should i have to add these files.
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 DirectorySize
{
public partial class Form1 : Form
{
delegate void SetStatusbarCallback(string text);
private DataTable m_dirs = new DataTable();
private Dictionary m_dirsSize = new Dictionary();
#region Form
public Form1()
{
InitializeComponent();
}
private void Form1_Resize(object sender, EventArgs e)
{
if (Form1.ActiveForm != null)
{
grdDirectories.Width = (Form1.ActiveForm.Width / 2) - 4;
grdFiles.Width = (Form1.ActiveForm.Width / 2) - 4;
grdFiles.Left = (Form1.ActiveForm.Width / 2);
}
}
private void Form1_Load(object sender, EventArgs e)
{
this.Width = Properties.Settings.Default.ProgramWidth;
this.Height = Properties.Settings.Default.ProgramHeight;
if (Properties.Settings.Default.ProgramLeft > -100)
{
this.Left = Properties.Settings.Default.ProgramLeft;
this.Top = Properties.Settings.Default.ProgramTop;
}
txtFolder.Text = Properties.Settings.Default.Directory;
grdDirectories.Width = (this.Width / 2) - 4;
grdFiles.Width = (this.Width / 2) - 4;
grdFiles.Left = (this.Width / 2);
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
Properties.Settings.Default.ProgramWidth = this.Width;
Properties.Settings.Default.ProgramHeight = this.Height;
Properties.Settings.Default.ProgramLeft = this.Left;
Properties.Settings.Default.ProgramTop = this.Top;
Properties.Settings.Default.Save();
}
#endregion
#region Scan Directory
#region Buttons
private void btnScan_Click(object sender, EventArgs e)
{
if (!Directory.Exists(txtFolder.Text))
{
MessageBox.Show("The folder does not exist.");
txtFolder.Focus();
return;
}
Properties.Settings.Default.Directory = txtFolder.Text;
Properties.Settings.Default.Save();
btnCancel.Enabled = true;
btnScan.Enabled = false;
txtFolder.Enabled = false;
toolStripProgressBar1.Visible = true;
toolStripProgressBar1.Value = 0;
this.Cursor = Cursors.WaitCursor;
this.backgroundWorker1.RunWorkerAsync();
}
private void btnBrowse_Click(object sender, EventArgs e)
{
if (txtFolder.Text.Trim() != "")
folderBrowserDialog1.SelectedPath = txtFolder.Text.Trim();
if (folderBrowserDialog1.ShowDialog() == DialogResult.OK)
txtFolder.Text = folderBrowserDialog1.SelectedPath;
}
private void btnCancel_Click(object sender, EventArgs e)
{
this.btnCancel.Enabled = false;
this.backgroundWorker1.CancelAsync();
}
#endregion
///
/// Controls in Windows Forms are bound to a specific thread and are not thread safe.
/// Therefore, if you are calling a control's method from a different thread, you must
/// use one of the control's invoke methods to marshal the call to the proper thread.
///
///
private void SetStatusBar(string text)
{
if (this.statusStrip1.InvokeRequired)
{
SetStatusbarCallback d = new SetStatusbarCallback(SetStatusBar);
this.Invoke(d, new object[] { text });
}
else
{
this.toolStripStatusLabel1.Text = text;
}
}
///
/// The method that does all the work.
///
/// The directory to search from.
///
private bool LoopFolder(DirectoryInfo[] dis)
{
if (this.backgroundWorker1.CancellationPending)
return false;
foreach (DirectoryInfo di in dis)
{
if (this.backgroundWorker1.CancellationPending)
return false;
string fullname = di.FullName;
SetStatusBar(fullname);
double size = GetFilesSize(di);
DataRow dr = m_dirs.NewRow();
dr["Name"] = fullname;
dr["Size"] = size;
m_dirs.Rows.Add(dr);
m_dirsSize.Add(fullname, size);
// sum up the fullsize on all parents
DirectoryInfo parent = di.Parent;
while (parent != null && !this.backgroundWorker1.CancellationPending)
{
if (m_dirsSize.ContainsKey(parent.FullName))
{
m_dirsSize[parent.FullName] += size;
parent = parent.Parent;
}
else
break;
}
toolStripProgressBar1.PerformStep();
}
return true;
}
///
/// Gets the total size of all files in the directory.
///
///
///
private double GetFilesSize(DirectoryInfo di)
{
double size = 0.0;
long lSize = 0;
foreach (FileInfo fi in di.GetFiles())
lSize += fi.Length;
size = Convert.ToDouble(lSize) / 1024.0 / 1024.0; // size in MB
return size;
}
#region BackgroundWorker
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
// Do not access the form's BackgroundWorker reference directly.
// Instead, use the reference provided by the sender parameter.
BackgroundWorker bw = sender as BackgroundWorker;
// Extract the argument.
//string[] args = (string[])e.Argument;
m_dirs = new DataTable();
m_dirsSize.Clear();
m_dirs.Columns.Add("Name", typeof(string));
m_dirs.Columns.Add("Size", typeof(double));
m_dirs.Columns.Add("Fullsize", typeof(double));
// Start the time-consuming operation.
DirectoryInfo di = new DirectoryInfo(txtFolder.Text);
DirectoryInfo[] dis = di.GetDirectories("*", SearchOption.AllDirectories);
toolStripProgressBar1.Maximum = dis.Length;
e.Result = LoopFolder(dis);
// If the operation was canceled by the user,
// set the DoWorkEventArgs.Cancel property to true.
if (bw.CancellationPending)
{
e.Cancel = true;
}
}
private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
btnCancel.Enabled = false;
btnScan.Enabled = true;
txtFolder.Enabled = true;
toolStripProgressBar1.Visible = false;
this.Cursor = Cursors.Default;
if (e.Cancelled)
{
// The user canceled the operation.
MessageBox.Show("Operation was canceled");
}
else if (e.Error != null)
{
// There was an error during the operation.
string msg = String.Format("An error occurred: {0}", e.Error.Message);
MessageBox.Show(msg);
}
else
{
foreach (DataRow dr in m_dirs.Rows)
{
dr["Size"] = Math.Round((double)dr["Size"], 2);
string fullname = (string)dr["Name"];
if (m_dirsSize.ContainsKey(fullname))
dr["Fullsize"] = Math.Round(m_dirsSize[fullname], 2);
}
m_dirs.DefaultView.Sort = "Size desc";
grdDirectories.DataSource = m_dirs;
toolStripStatusLabel1.Text = m_dirsSize.Count + " directories found.";
}
}
#endregion
#endregion
#region Show files
private void grdDirectories_SelectionChanged(object sender, EventArgs e)
{
if (grdDirectories.SelectedRows.Count == 1)
{
string directory = grdDirectories.SelectedRows[0].Cells[0].Value.ToString();
toolStripStatusLabel1.Text = directory;
DataTable tblFiles = new DataTable();
tblFiles.Columns.Add("Name", typeof(string));
tblFiles.Columns.Add("Size", typeof(double));
tblFiles.Columns.Add("LastAccessTime", typeof(DateTime));
tblFiles.Columns.Add("LastWriteTime", typeof(string));
tblFiles.Columns.Add("CreationTime", typeof(string));
tblFiles.Columns.Add("ReadOnly", typeof(bool)).ReadOnly = true;
tblFiles.Columns.Add("Ext", typeof(string));
DirectoryInfo di = new DirectoryInfo(directory);
foreach (FileInfo fi in di.GetFiles())
{
DataRow dr = tblFiles.NewRow();
dr["Name"] = fi.Name;
dr["LastAccessTime"] = fi.LastAccessTime;
dr["Size"] = Math.Round(fi.Length / 1024.0 / 1024.0, 2); // size in MB
dr["LastWriteTime"] = fi.LastWriteTime;
dr["ReadOnly"] = fi.IsReadOnly;
dr["CreationTime"] = fi.CreationTime;
dr["Ext"] = fi.Extension;
tblFiles.Rows.Add(dr);
}
tblFiles.DefaultView.Sort = "Size desc";
grdFiles.DataSource = tblFiles;
}
}
#endregion
}
|
|
|
|
|
You might want to read everything in this post[^] first, specifically point number 4.
You're code doesn't have anything in it to handle errors, specifically, Try/Catch blocks that would catch the specific errors, at specific points in your code, that your getting.
Dave Kreskowiak
Microsoft MVP
Visual Developer - Visual Basic 2006, 2007
|
|
|
|
|
i understand the rules but as you see my question is 2 lines
and i don't know where should i send and i sended all of it
|
|
|
|
|
I am making program using .NETCF
I want to make a feature which is able to download a file. To specify the location where the file can be saved, i use savefiledialog tool. But it's always saves the file to the my Device folder of the PDA.
Whereas i want to make it flexible so that the user can choose the location to save the file. I try to look for the property of the savefiledialog which reflect the location to save the file. but i can't. any help please ...
i wish to learn more from this forum
|
|
|
|
|
Introduction
It is often a common requirement in a web application to have the
ability to download a some sort of file to the clients computer. This article
will illustrate how to create and download a text file to the users computer.
Using the code
Although in the example I actually create the text file before I
stream it out to the client, I feel it is important to highlight that you don't
necessarily have to do this, as the file could actually exist on the file system
and you may want to stream it out to the client. If that is the case you may one
need to use the FileStream to read the already existing document.
We first open the file for reading and we actually read the file byte
for byte into stream, then once we have the file into a stream, we basically
then just use the Response object and download the file via the output
stream.
Response.AddHeader("Content-disposition", "attachment; filename=" + sGenName);
Response.ContentType = "application/octet-stream";
Response.BinaryWrite(btFile);
Response.End();
The real power in this snippet is in the lines above, by adding
header, you are telling the browser to download the file as an attachment. Then
you set The ContentType header which is added, sets your
MIME type so that the browser knows what kind of file it is
about to download. One can choose any of the following MIME types for the
browser.
".asf" = "video/x-ms-asf"
".avi" = "video/avi"
".doc" = "application/msword"
".zip" = "application/zip"
".xls" = "application/vnd.ms-excel"
".gif" = "image/gif"
".jpg"= "image/jpeg"
".wav" = "audio/wav"
".mp3" = "audio/mpeg3"
".mpg" "mpeg" = "video/mpeg"
".rtf" = "application/rtf"
".htm", "html" = "text/html"
".asp" = "text/asp"
'Handle All Other Files
= "application/octet-stream"
A full example of how to go about downloading a text file could like
the code below.
C#
Collapse
protected void Button1_Click(object sender, EventArgs e)
{
string sFileName = System.IO.Path.GetRandomFileName();
string sGenName = "Friendly.txt";
using (System.IO.StreamWriter SW = new System.IO.StreamWriter(Server.MapPath("TextFiles/" + sFileName + ".txt")))
{
SW.WriteLine(txtText.Text);
SW.Close();
}
System.IO.FileStream fs = null;
fs = System.IO.File.Open(Server.MapPath("TextFiles/" + sFileName + ".txt"), System.IO.FileMode.Open);
byte[] btFile = new byte[fs.Length];
fs.Read(btFile, 0, Convert.ToInt32(fs.Length));
fs.Close();
Response.AddHeader("Content-disposition", "attachment; filename=" + sGenName);
Response.ContentType = "application/octet-stream";
Response.BinaryWrite(btFile);
Response.End();
}
VB.NET
Collapse
Dim strFileName As String = System.IO.Path.GetRandomFileName()
Dim strFriendlyName As String = "Friendly.txt"
Using sw As New System.IO.StreamWriter(Server.MapPath("TextFiles/" + strFileName + ".txt"))
sw.WriteLine(txtText.Text)
sw.Close()
End Using
Dim fs As System.IO.FileStream = Nothing
fs = System.IO.File.Open(Server.MapPath("TextFiles/" + strFileName + ".txt"), System.IO.FileMode.Open)
Dim btFile(fs.Length) As Byte
fs.Read(btFile, 0, fs.Length)
fs.Close()
With Response
.AddHeader("Content-disposition", "attachment;filename=" & strFriendlyName)
.ContentType = "application/octet-stream"
.BinaryWrite(btFile)
.End()
end with
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
' string sFileName = System.IO.Path.GetRandomFileName();
Dim sFileName As String
sFileName = System.IO.Path.GetTempFileName
' string sGenName = "Friendly.txt";
Dim sGenName As String = "Friendly.txt"
'YOu could omit these lines here as you may not want to save the textfile to the server
'I have just left them here to demonstrate that you could create the text file
'dim System.IO.StreamWriter SW = new System.IO.StreamWriter(Server.MapPath("TextFiles/" + sFileName + ".txt")))
Dim sw As System.IO.StreamWriter
sw = New System.IO.StreamWriter(Server.MapPath("TextFiles/" + sFileName + ".txt"))
sw.WriteLine("sdfdsfdfsdfsdafasdfasd")
'SW.WriteLine(txtText.Text);
sw.Close()
' System.IO.FileStream(fs = null)
Dim fs As System.IO.FileStream
' fs = 0
fs = System.IO.File.Open(Server.MapPath("TextFiles/" + sFileName + ".txt"), System.IO.FileMode.Open)
' byte[] btFile = new byte[fs.Length];
Dim btFile(fs.Length) As Byte
fs.Read(btFile, 0, Convert.ToInt32(fs.Length))
fs.Close()
Response.AddHeader("Content-disposition", "attachment; filename=" + sGenName)
Response.ContentType = "application/octet-stream"
Response.BinaryWrite(btFile)
Response.End()
End Sub
|
|
|
|
|
Next time, just supply the link to the article. Do NOT copy and pase the whole thing into a forum post!
Dave Kreskowiak
Microsoft MVP
Visual Developer - Visual Basic 2006, 2007
|
|
|
|
|
Write this code according to ur requirment in button click event. when user click the button than save dialog open and user easily save the file where he want.try to understand by this conde in vb.net
Function saveCopyLocal(ByVal FSaveURL)
'source file
Dim strSrcFileName As String = "\foldername\" + FSaveURL + ".txt"
'targat file
Dim strTargetName As String = "Rapid_reporting_Pilot.txt"
Try
Dim fs As System.IO.FileStream
fs = System.IO.File.Open(Server.MapPath(strSrcFileName), System.IO.FileMode.Open)
Dim btFile(fs.Length) As Byte
fs.Read(btFile, 0, fs.Length)
fs.Close()
With Response
.AddHeader("Content-disposition", "attachment;filename=" & strTargetName)
.ContentType = "text/txt"
.BinaryWrite(btFile)
.End()
End With
Catch ex As Exception
End Try
End Function
|
|
|
|
|
Wirte this code in button event click event and when user click the button the a save dialog will be open and user can easily save the file.
Function saveCopyLocal(ByVal FSaveURL)
'strSrcFileNmae=source file name with relative path
Dim strSrcFileName As String = "\folderName\" + FSaveURL + ".txt"
'strTargetName=name of file from which name u like to save and user can 'aslso change the name
Dim strTargetName As String = "Rapid_reporting_Pilot.txt"
' Dim sw As System.IO.StreamWriter
' sw = New System.IO.StreamWriter(Server.MapPath(strSrcFileName))
' sw.Close()
Try
' Dim fs As System.IO.FileStream = Nothing
Dim fs As System.IO.FileStream
fs = System.IO.File.Open(Server.MapPath(strSrcFileName), System.IO.FileMode.Open)
Dim btFile(fs.Length) As Byte
fs.Read(btFile, 0, fs.Length)
fs.Close()
With Response
.AddHeader("Content-disposition", "attachment;filename=" & strTargetName)
.ContentType = "text/txt"
.BinaryWrite(btFile)
.End()
End With
Catch ex As Exception
End Try
End Function
|
|
|
|
|
Dude, do you have any clue how to use a forum??
Dave Kreskowiak
Microsoft MVP
Visual Developer - Visual Basic 2006, 2007
|
|
|
|
|
Ow ... thanks !!
Finally it works
yea ... beside of the nice FileStream and StreamWriter explanation I got from you, I make some modification on it. The location is easily detected by saveFileDialog1.FileName()
not only the file name, but also the selected directory path can be retrieved. Thanks ... !
|
|
|
|
|
i need help about how we hide desktop and task bar in vb.net
|
|
|
|
|
Hope this Link[^]will help you in your developing application.
Regards,
Satips.
|
|
|
|
|
very thankx for help me i am checking this link if u have more information about this in vb.net than tell me.i am waiting ur reply
|
|
|
|
|
In an ASP.NET (Web Forms) app, that's simply not possible.
Dave Kreskowiak
Microsoft MVP
Visual Developer - Visual Basic 2006, 2007
|
|
|
|
|
than u can helpe to guide me in vb.net
|
|
|
|
|
I repeat, in an ASP.NET app, no matter what language it's written in, it's not possible to hide the users Task Bar and/or Desktop.
Dave Kreskowiak
Microsoft MVP
Visual Developer - Visual Basic 2006, 2007
|
|
|
|
|
I have done a project in VB.Net and Access. Where I have to show the Report to Excel from ACCESS thru VB.Net
Please give me the code to print data to excel
|
|
|
|
|
Iam designing a form with labels and Textboxes.
The TExt of the label is long. SO I have to set Wrap text for the labels.
Please tell me how to set wrap text for a label in VB.NET
|
|
|
|
|
This probably isn't the best example, but it's the only thing I could think of:
Dim StartVar As Integer = 5
Dim EndVar As Integer = Label1.Text.Length
Dim Tempstring As String
While Not StartVar < 5
Tempstring = Label1.Text.Insert(StartVar, ControlChars.NewLine)
Label1.Text = Tempstring
StartVar += 5
If StartVar >= EndVar Then
Exit While
End If
End While
This example inserts a new line every 5 characters, and then stops if it runs out of characters. Just replace StartVar with the number of characters you want to have on each line of your label.
Hope this helps!
Trinity: Neo... nobody has ever done this before.
Neo: That's why it's going to work.
|
|
|
|
|
You can turn the AutoSize property off, the set the size of the label yourself. With AutoSize turned off, the label control does automatic word wrap.
Dave Kreskowiak
Microsoft MVP
Visual Developer - Visual Basic 2006, 2007
|
|
|
|
|
Colleagues,
Is there a reusable generic VB6 form/dialog for COM port configuration (like a port settings dialog in the HyperTerminal)? It would have: baud rate, data bits, parity etc. I couldn’t find something like that with Google (neither DLL nor source code).
Thanks,
Nick
P.S. If it doesn’t exist, I’ll write one and post it on Code Project.
-- modified at 0:04 Wednesday 25th April, 2007
|
|
|
|
|
Nick Alexeev wrote: Is there a reusable generic VB6 form/dialog for COM port configuration
Nope. You'll have to make your own.
Dave Kreskowiak
Microsoft MVP
Visual Developer - Visual Basic 2006, 2007
|
|
|
|
|
|
Hello i am trying to make a Internet browser that I can use on my school computers. I have made the browser and everything its just that I need to know how I can make my browser work on a proxies so I can get around the blockers. I am using Visual Studios 2005.
I also need to know how I can make it so that I have .net framework in the program so just in case its not install on the computer that the browser is running on.
I type in a strange way so if you need to me wright back explaining in more detail just ask.
|
|
|
|
|
itsryan wrote: how I can make my browser work on a proxies so I can get around the blockers.
The blockers are there for a reason. You need access to a proxy outside the school network, which, if the IT staff has any brains, have blocked access to those too. You can NOT get around the firewalls and proxies your school is using.
itsryan wrote: I also need to know how I can make it so that I have .net framework in the program so just in case its not install on the computer that the browser is running on.
There is nothing in the .NET Framework that does this. There are a few third party products that do do this, but they cost big $$$, on the order of $500 per developer.
Dave Kreskowiak
Microsoft MVP
Visual Developer - Visual Basic 2006, 2007
|
|
|
|
|