Folder Copy Error:System.UnauthorizedAccessException in C# - c#

I want to copy an existing file to another destination, but it gives an access error.
Error Name:
System.UnauthorizedAccessException
I understand that I need to grant access but I don't know how to do this.
My project looks like:
I will put the file on the server and run this program from the web-based program. I will close the button and textbox with the source file. I will only leave the target forms open
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;
namespace WindowsFormsApp1
{
public partial class Form1 : Form
{
BackgroundWorker worker = new BackgroundWorker();
public Form1()
{
InitializeComponent();
worker.WorkerReportsProgress = true;
worker.WorkerSupportsCancellation = true;
worker.ProgressChanged += Worker_ProgressChanged;
worker.DoWork += Worker_DoWork;
}
void Copyfile(string source, string des)
{
FileStream fsOut = new FileStream(des, FileMode.Create);
FileStream fsIn = new FileStream(source, FileMode.Open);
byte[] bt = new byte[1048456];
int readByte;
while ((readByte = fsIn.Read(bt, 0, bt.Length)) > 0)
{
fsOut.Write(bt,0,readByte);
worker.ReportProgress((int)(fsIn.Position * 100 / fsIn.Length));
}
fsIn.Close();
fsOut.Close();
}
private void Worker_DoWork(object sender, DoWorkEventArgs e)
{
Copyfile(txtSource.Text, txtTarget.Text);
}
private void Worker_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
progressBar1.Value = e.ProgressPercentage;
label1.Text = progressBar1.Value.ToString() + "%";
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
FolderBrowserDialog fbd1 = new FolderBrowserDialog();
if (fbd1.ShowDialog() == DialogResult.OK)
{
txtSource.Text = Path.Combine(fbd1.SelectedPath, Path.GetFileName(txtTarget.Text));
}
}
private void button2_Click(object sender, EventArgs e)
{
worker.RunWorkerAsync();
}
private void button3_Click(object sender, EventArgs e)
{
FolderBrowserDialog fbd = new FolderBrowserDialog();
if (fbd.ShowDialog() == DialogResult.OK)
{
txtTarget.Text = Path.Combine(fbd.SelectedPath, Path.GetFileName(txtSource.Text));
}
}
}
}

I added and changed some codes
public static void CopyAll(DirectoryInfo source, DirectoryInfo target)
{
Directory.CreateDirectory(target.FullName);
// HER DOSYAYI YENI DIZINE KOPYALAR
foreach (FileInfo fi in source.GetFiles())
{
fi.CopyTo(System.IO.Path.Combine(target.FullName, fi.Name), true);
}
// HER ALT DIZINI KOPYALAR
foreach (DirectoryInfo diSourceSubDir in source.GetDirectories())
{
DirectoryInfo nextTargetSubDir =
target.CreateSubdirectory(diSourceSubDir.Name);
CopyAll(diSourceSubDir, nextTargetSubDir);
}
}
void CopyFile(string source, string des)
{
FileStream fsout = new FileStream(des, FileMode.Create);
FileStream fsIn = new FileStream(source, FileMode.Open);
byte[] bt = new byte[1048756];
int readByte;
while ((readByte=fsIn.Read(bt, 0, bt.Length))>0)
{
fsout.Write(bt, 0, readByte);
worker.ReportProgress((int)(fsIn.Position*100/fsIn.Length));
}
fsIn.Close();
fsout.Close();
}
private void Worker_DoWork(object sender, DoWorkEventArgs e)
{
CopyAll(new DirectoryInfo( txtSource.Text), new DirectoryInfo(txtTarget.Text));
}
I add my github repository:https://github.com/yusufcelik1/Copy-Folder.git

Related

Save File to .txt after finishing operation

I already got most of the help I needed in order to create a working button to save my scraped proxies to a .txt file, but I still run into one issue. This is the code that I have gotten so far, it works perfectly fine:
using System;
using System.Text;
using System.Text.RegularExpressions;
using System.Net;
using System.Windows.Forms;
using System.IO;
namespace CyberScraper
{
public partial class Base_Scraper : Form
{
WebClient _WC = new WebClient();
Defaults _DF = new Defaults();
public Base_Scraper()
{
CheckForIllegalCrossThreadCalls = false;
InitializeComponent();
}
private void Base_Scraper_Load(object sender, EventArgs e)
{
MessageBox.Show("twitch.tv/CyberLost same YT Name");
}
private void ScrapeTheProxies()
{
try
{
foreach (string Source in ScrapeSources.Lines)
{
string UnparsedWebSource = _WC.DownloadString(Source);
MatchCollection _MC = _DF.REGEX.Matches(UnparsedWebSource);
foreach (Match Proxy in _MC)
{
GatheredProxies.Items.Add(Proxy);
}
}
}
catch (Exception)
{
}
}
private void SaveProxyResults_Click(object sender, System.EventArgs e)
{
Stream myStream;
SaveFileDialog dlg = new SaveFileDialog();
dlg.Title = "";
dlg.InitialDirectory = #"C:\Users\username\Desktop";
dlg.Filter = "txt files (*.txt)|*.txt";
dlg.FilterIndex = 1;
if (dlg.ShowDialog() == DialogResult.OK)
{
if ((myStream = dlg.OpenFile()) != null)
{
myStream.Close();
StreamWriter writer = new StreamWriter(dlg.FileName);
for (int i = 0; i < GatheredProxies.Items.Count; i++)
{
writer.WriteLine((string)GatheredProxies.Items[i]);
}
writer.Close();
}
}
dlg.Dispose();
}
private void BackgroundWorker_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e)
{
ScrapeTheProxies();
}
private void ScrapeButton_Click(object sender, EventArgs e)
{
BackgroundWorker.RunWorkerAsync();
}
}
}
When I click on "Save Results" it works before I scraped the proxies, if I do it after finishing scraping the proxies it outputs this error and saves it on the desktop as an empty .txt file instead of a .txt file containing the scraped proxies:
System.InvalidCastException: 'Unable to cast object of type 'System.Text.RegularExpressions.Match' to type 'System.String'.'
in:
writer.WriteLine((string)GatheredProxies.Items[i]);

save data to .txt file at the same time click "read" button

i want to save received data to .txt file when click "read" button. please help me
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.Threading;
using System.IO.Ports;
namespace Serial
{
public partial class Form1 : Form
{
static SerialPort serialPort1;
public Form1()
{
InitializeComponent();
getAvailablePorts();
serialPort1 = new SerialPort();
}
void getAvailablePorts()
{
string[] Ports = SerialPort.GetPortNames();
comboBox1.Items.AddRange(Ports);
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void button3_Click(object sender, EventArgs e)
{
try
{
if (comboBox1.Text == "" || comboBox2.Text == "")
{
textBox2.Text = "Please select port Setting";
}
else
{
serialPort1.PortName = comboBox1.Text;
serialPort1.BaudRate = Convert.ToInt32(comboBox2.Text);
serialPort1.Open();
progressBar1.Value = 100;
button1.Enabled = true;
button2.Enabled = true;
textBox1.Enabled = true;
button3.Enabled = false;
button4.Enabled = true;
}
}
catch (UnauthorizedAccessException)
{
textBox2.Text = "anauthorized Acess";
}
}
private void button4_Click(object sender, EventArgs e)
{
serialPort1.Close();
progressBar1.Value = 0;
button1.Enabled = false;
button2.Enabled = false;
button4.Enabled = false;
button3.Enabled = true;
textBox1.Enabled = false;
}
private void button1_Click(object sender, EventArgs e)
{
serialPort1.WriteLine(textBox1.Text);
textBox1.Text = "";
}
private void button2_Click(object sender, EventArgs e)
{
try
{
textBox2.Text = serialPort1.ReadLine();
}
catch(TimeoutException)
{
textBox2.Text = "Timeout Exception";
}
}
}
}
Simply use File.WriteAllText.Sample :
File.WriteAllText("path here","text here")
Just use StreamWriter
using(StreamWriter sw = new StreamWriter("filename.txt")){
sw.WriteLine(textbox.Text);
sw.Close();
}

C# how to fix this

I have a error that I don't no how to fix. I would perfer the answer in code. This is the error, Error 1 No overload for
'turnToVideoToolStripMenuItem_Click' matches delegate 'System.EventHandler'
C:\Users\kinoa\documents\visual studio 2013\Projects\Armored Animation Studio\Armored Animation Studio\main.Designer.cs 259 56 Armored Animation Studio.
This is the code,
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 NReco.VideoConverter;
using System.Diagnostics;
using System.IO;
namespace Armored_Animation_Studio
{
public partial class main : Form
{
public Point current = new Point();
public Point old = new Point();
public Graphics g;
public Pen p = new Pen(Color.Black, 5);
public List<Image> Animation = new List<Image>();
public main()
{
InitializeComponent();
g = panel1.CreateGraphics();
p.SetLineCap(System.Drawing.Drawing2D.LineCap.Round,
System.Drawing.Drawing2D.LineCap.Round,
System.Drawing.Drawing2D.DashCap.Round);
}
private void panel1_MouseMove(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
current = e.Location;
g.DrawLine(p, current, old);
old = current;
}
}
private void panel1_MouseDown(object sender, MouseEventArgs e)
{
old = e.Location;
if(radioButton1.Checked)
{
p.Width = 1;
}
else if(radioButton2.Checked)
{
p.Width = 5;
}
else if (radioButton3.Checked)
{
p.Width = 10;
}
else if (radioButton4.Checked)
{
p.Width = 15;
}
else if (radioButton5.Checked)
{
p.Width = 30;
}
}
private void button1_Click(object sender, EventArgs e)
{
ColorDialog cd = new ColorDialog();
if (cd.ShowDialog() == DialogResult.OK)
p.Color = cd.Color;
}
private void button3_Click(object sender, EventArgs e)
{
panel1.Invalidate();
}
private void radioButton7_CheckedChanged(object sender, EventArgs e)
{
p.Color = System.Drawing.Color.White;
}
private void button2_Click(object sender, EventArgs e)
{
Bitmap bmp = new Bitmap(panel1.Width, panel1.Height);
panel1.DrawToBitmap(bmp, new Rectangle(0, 0, panel1.Width,
panel1.Height));
Animation.Add(bmp);
}
private void turnToVideoToolStripMenuItem_Click(object sender, EventArgs
e, string [] args)
{
Process proc = new Process();
proc.StartInfo.FileName = "ffmpeg";
proc.StartInfo.Arguments = "-i " + args[0] + " " + args[1];
proc.StartInfo.RedirectStandardError = true;
proc.StartInfo.UseShellExecute = false;
if (!proc.Start())
{
Console.WriteLine("Error starting");
return;
}
StreamReader reader = proc.StandardError;
string line;
while ((line = reader.ReadLine()) != null)
{
Console.WriteLine("ffmpeg -i <imagefile> -vcodec mpeg4 out_movie");
}
proc.Close();
}
}
}
Thank you!
Change the method signature:
private void turnToVideoToolStripMenuItem_Click(object sender, EventArgs e, string [] args)
to:
private void turnToVideoToolStripMenuItem_Click(object sender, EventArgs e)
Would take care of the compiler error, but you are left with getting to the data that you expected to be in args. What are you expecting to be passed in that last parameter?

Getting,reading,writing, and saving into one .txt file a collection of .txt documents contents. in visual c# using windows form

am new to c#,Here am trying to read multiple txt files with its contents at once, then using textbox to collect all the txt content, after collecting the content then I will save all the content back into once txt file. below is my code, pls help out.
Here is the interface of the app
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;
namespace FileSaver
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void panel2_Paint(object sender, PaintEventArgs e)
{
}
private void label1_Click(object sender, EventArgs e)
{
}
//File 004: Save the File in System Temporary path
private void button2_Click(object sender, EventArgs e)
{
if (txtFileContent.Visible == true)
{
SaveFile(Path.GetTempPath());
}
else
MessageBox.Show("This form saves only text files");
}
//File 001: Use File open dialog to get the file name
private void btn_File_Open_Click(object sender, EventArgs e)
{
List<String> MyStream = new List<string>();
string ext = "";
this.dlgFileOpen.Filter = "Text Files(*.txt) | *.txt";
this.dlgFileOpen.Multiselect = true;
if (dlgFileOpen.ShowDialog() == DialogResult.OK)
{
try
{
StringBuilder stbuilder = new StringBuilder();
foreach (var files in dlgFileOpen.SafeFileNames )
{
MyStream.Add(files + "\n");
Console.WriteLine();
}
foreach (var item in MyStream)
{
stbuilder.Append(item );
}
txtSelectedFile.Text = stbuilder.ToString() ;
ext = Path.GetExtension(dlgFileOpen.FileName);
}
catch (Exception ex)
{
MessageBox.Show("Error: Could not read file from disk. Original error: " + ex.Message);
}
if (ext == ".txt")
{
//003: The extension is txt. Read the file and display the content
txtFileContent.Visible = true;
FileStream filestream = new FileStream(dlgFileOpen.FileName, FileMode.Open);
StreamReader streamReader = new StreamReader(filestream);
while (streamReader.EndOfStream != true)
{
txtFileContent.AppendText(streamReader.ReadLine());
txtFileContent.AppendText(Environment.NewLine);
}
streamReader.Close();
}
}
}
private void txtSelectedFile_TextChanged(object sender, EventArgs e)
{
}
//File 002: Use the Path object to determine the selected file has the
// required extension.
private void dlgFileOpen_FileOk(object sender, CancelEventArgs e)
{
string Required_Ext = ".txt ";
string selected_ext = Path.GetExtension(dlgFileOpen.FileName);
int index = Required_Ext.IndexOf(selected_ext);
//002: Inform the user to select correct extension
if (index < 0)
{
MessageBox.Show("Extension Maaaan... Extension! Open only txt or bmp or jpg");
e.Cancel = true;
}
}
private void folderBrowserDialog1_HelpRequest(object sender, EventArgs e)
{
}
private void SaveFile_Click(object sender, EventArgs e)
{
//001: Setup the Folder dialog properties before the display
string selected_path = "";
dlgFolder.Description = "Select a Folder for Saving the text file";
dlgFolder.RootFolder = Environment.SpecialFolder.MyComputer;
//002: Display the dialog for folder selection
if (dlgFolder.ShowDialog() == DialogResult.OK)
{
selected_path = dlgFolder.SelectedPath;
if (string.IsNullOrEmpty(selected_path) == true)
{
MessageBox.Show("Unable to save. No Folder Selected.");
return;
}
}
//003: Perform the File saving operation. Make sure text file is displayed before saving.
if (txtFileContent.Visible == true)
{
SaveFile(selected_path);
}
else
MessageBox.Show("This form saves only text files");
}
public void SaveFile(string selected_path)
{
string Save_File;
if (selected_path.Length > 3)
Save_File = selected_path + "\\" + txtSaveFile.Text + ".txt";
else
Save_File = selected_path + txtSaveFile.Text + ".txt";
FileStream fstream = new FileStream(Save_File, FileMode.CreateNew);
StreamWriter writer = new StreamWriter(fstream);
writer.Write(txtFileContent.Text);
lblSavedLocation.Text = "Text File Saved in " + Save_File;
writer.Close();
}
private void txtSaveFile_TextChanged(object sender, EventArgs e)
{
}
}
}
Try this out. I stripped out all the the code i felt unnecessary for your problem:
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;
namespace FileSaver
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void panel2_Paint(object sender, PaintEventArgs e)
{
}
private void label1_Click(object sender, EventArgs e)
{
}
//File 004: Save the File in System Temporary path
private void button2_Click(object sender, EventArgs e)
{
if (txtFileContent.Visible == true)
{
SaveFile(Path.GetTempPath());
}
else
MessageBox.Show("This form saves only text files");
}
//File 001: Use File open dialog to get the file name
private void btn_File_Open_Click(object sender, EventArgs e)
{
this.dlgFileOpen.Filter = "Text Files(*.txt) | *.txt";
this.dlgFileOpen.Multiselect = true;
if (dlgFileOpen.ShowDialog() == DialogResult.OK)
{
var stBuilder = new StringBuilder();
foreach (var fileName in dlgFileOPen.FileNames)
{
stBuilder.AppendLine(File.ReadAllText(fileName));
}
txtFileContent.Text = stBuilder.ToString();
}
}
private void txtSelectedFile_TextChanged(object sender, EventArgs e)
{
}
//File 002: Use the Path object to determine the selected file has the
// required extension.
private void dlgFileOpen_FileOk(object sender, CancelEventArgs e)
{
}
private void folderBrowserDialog1_HelpRequest(object sender, EventArgs e)
{
}
private void SaveFile_Click(object sender, EventArgs e)
{
//001: Setup the Folder dialog properties before the display
string selected_path = "";
dlgFolder.Description = "Select a Folder for Saving the text file";
dlgFolder.RootFolder = Environment.SpecialFolder.MyComputer;
//002: Display the dialog for folder selection
if (dlgFolder.ShowDialog() == DialogResult.OK)
{
selected_path = dlgFolder.SelectedPath;
if (string.IsNullOrEmpty(selected_path) == true)
{
MessageBox.Show("Unable to save. No Folder Selected.");
return;
}
}
//003: Perform the File saving operation. Make sure text file is displayed before saving.
if (txtFileContent.Visible == true)
{
SaveFile(selected_path);
}
else
MessageBox.Show("This form saves only text files");
}
public void SaveFile(string selected_path)
{
string Save_File;
if (selected_path.Length > 3)
Save_File = selected_path + "\\" + txtSaveFile.Text + ".txt";
else
Save_File = selected_path + txtSaveFile.Text + ".txt";
File.WriteAllText(Save_File, txtFileContent.Text);
lblSavedLocation.Text = "Text File Saved in " + Save_File;
}
private void txtSaveFile_TextChanged(object sender, EventArgs e)
{
}
}
}
All looks good, except for the reading part, it can be done in a much easier way....
StringBuilder stbuilder = new StringBuilder();
foreach (var filePath in dlgFileOpen.FileNames)
{
StreamReader sr = new StreamReader(filePath);
stbuilder.Append(sr.ReadToEnd());
sr.Close();
//Or Much faster you can use
stbuilder.Append(File.ReadAllText(filePath));
stbuilder.Append(Environment.NewLine);
stbuilder.Append(Environment.NewLine);
txtFileContent.Text = stbuilder.ToString();
}

How to Record WebCam Video in MPEG or AVI files using C# Desktop Application

I am developing a Desktop Application which requires me to connect to webcam(s) and record(save) the video in MPEG, AVI, MP4 and WMV formats and Burn into the CD/DVD. The application is in Win Forms. I am only Looking for free or open source solutions or controls.
I had done saving as AVI using Aforge.Net but its taking more size to save(like 60-100MB for 15sce 320x240 Video ). I am expecting 1MB for 10sec.
Here is the Code :
using System;
using System.Drawing;
using System.Windows.Forms;
using AForge.Video;
using AForge.Video.DirectShow;
using AForge.Video.VFW;
namespace Aforge_Web_Cam
{
public partial class VideoForm : Form
{
private FilterInfoCollection VideoCaptureDevices;
private VideoCaptureDevice FinalVideo = null;
private VideoCaptureDeviceForm captureDevice;
private Bitmap video;
private AVIWriter AVIwriter = new AVIWriter();
private SaveFileDialog saveAvi;
public VideoForm()
{
InitializeComponent();
}
private void VideoForm_Load(object sender, EventArgs e)
{
VideoCaptureDevices = new FilterInfoCollection(FilterCategory.VideoInputDevice);
captureDevice = new VideoCaptureDeviceForm();
}
private void butStart_Click(object sender, EventArgs e)
{
if (captureDevice.ShowDialog(this) == DialogResult.OK)
{
VideoCaptureDevice videoSource = captureDevice.VideoDevice;
FinalVideo = captureDevice.VideoDevice;
FinalVideo.NewFrame += new NewFrameEventHandler(FinalVideo_NewFrame);
FinalVideo.Start();
}
}
void FinalVideo_NewFrame(object sender, NewFrameEventArgs eventArgs)
{
if (butStop.Text == "Stop Record")
{
video = (Bitmap)eventArgs.Frame.Clone();
pbVideo.Image = (Bitmap)eventArgs.Frame.Clone();
AVIwriter.Quality = 0;
AVIwriter.AddFrame(video);
}
else
{
video = (Bitmap)eventArgs.Frame.Clone();
pbVideo.Image = (Bitmap)eventArgs.Frame.Clone();
}
}
private void butRecord_Click(object sender, EventArgs e)
{
saveAvi = new SaveFileDialog();
saveAvi.Filter = "Avi Files (*.avi)|*.avi";
if (saveAvi.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
int h = captureDevice.VideoDevice.VideoResolution.FrameSize.Height;
int w = captureDevice.VideoDevice.VideoResolution.FrameSize.Width;
AVIwriter.Open(saveAvi.FileName, w, h);
butStop.Text = "Stop Record";
//FinalVideo = captureDevice.VideoDevice;
//FinalVideo.NewFrame += new NewFrameEventHandler(FinalVideo_NewFrame);
//FinalVideo.Start();
}
}
private void butStop_Click(object sender, EventArgs e)
{
if (butStop.Text == "Stop Record")
{
butStop.Text = "Stop";
if (FinalVideo == null)
{ return; }
if (FinalVideo.IsRunning)
{
//this.FinalVideo.Stop();
this.AVIwriter.Close();
pbVideo.Image = null;
}
}
else
{
this.FinalVideo.Stop();
this.AVIwriter.Close();
pbVideo.Image = null;
}
}
private void butCapture_Click(object sender, EventArgs e)
{
pbVideo.Image.Save("IMG" + DateTime.Now.ToString("hhmmss") + ".jpg");
}
private void butCancel_Click(object sender, EventArgs e)
{
this.Close();
}
private void VideoForm_FormClosing(object sender, FormClosingEventArgs e)
{
if (FinalVideo == null)
{ return; }
if (FinalVideo.IsRunning)
{
this.FinalVideo.Stop();
this.AVIwriter.Close();
}
}
}
}
AVIWriter doesn't provide videocompression, use FileWriter from AForge.Video.FFMPEG. There you can choose everything: Size, Framerate, Codec and Bitrate and if your video was 600MB in 20 sec it now will be 6 MB in 20 sec.
Here you go:
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 AForge.Video;
using AForge.Video.DirectShow;
using AForge.Video.FFMPEG;
using AForge.Video.VFW;
namespace WindowsFormsApplication12
{
public partial class Form1 : Form
{
private FilterInfoCollection VideoCaptureDevices;
private VideoCaptureDevice FinalVideo = null;
private VideoCaptureDeviceForm captureDevice;
private Bitmap video;
//private AVIWriter AVIwriter = new AVIWriter();
private VideoFileWriter FileWriter = new VideoFileWriter();
private SaveFileDialog saveAvi;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
VideoCaptureDevices = new FilterInfoCollection(FilterCategory.VideoInputDevice);
captureDevice = new VideoCaptureDeviceForm();
}
private void button1_Click(object sender, EventArgs e)
{
if (captureDevice.ShowDialog(this) == DialogResult.OK)
{
VideoCaptureDevice videoSource = captureDevice.VideoDevice;
FinalVideo = captureDevice.VideoDevice;
FinalVideo.NewFrame += new NewFrameEventHandler(FinalVideo_NewFrame);
FinalVideo.Start();
}
}
void FinalVideo_NewFrame(object sender, NewFrameEventArgs eventArgs)
{
if (butStop.Text == "Stop Record")
{
video = (Bitmap)eventArgs.Frame.Clone();
pictureBox1.Image = (Bitmap)eventArgs.Frame.Clone();
//AVIwriter.Quality = 0;
FileWriter.WriteVideoFrame(video);
//AVIwriter.AddFrame(video);
}
else
{
video = (Bitmap)eventArgs.Frame.Clone();
pictureBox1.Image = (Bitmap)eventArgs.Frame.Clone();
}
}
private void button2_Click(object sender, EventArgs e)
{
saveAvi = new SaveFileDialog();
saveAvi.Filter = "Avi Files (*.avi)|*.avi";
if (saveAvi.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
int h = captureDevice.VideoDevice.VideoResolution.FrameSize.Height;
int w = captureDevice.VideoDevice.VideoResolution.FrameSize.Width;
FileWriter.Open(saveAvi.FileName, w, h,25,VideoCodec.Default,5000000);
FileWriter.WriteVideoFrame(video);
//AVIwriter.Open(saveAvi.FileName, w, h);
butStop.Text = "Stop Record";
//FinalVideo = captureDevice.VideoDevice;
//FinalVideo.NewFrame += new NewFrameEventHandler(FinalVideo_NewFrame);
//FinalVideo.Start();
}
}
private void butStop_Click(object sender, EventArgs e)
{
if (butStop.Text == "Stop Record")
{
butStop.Text = "Stop";
if (FinalVideo == null)
{ return; }
if (FinalVideo.IsRunning)
{
//this.FinalVideo.Stop();
FileWriter.Close();
//this.AVIwriter.Close();
pictureBox1.Image = null;
}
}
else
{
this.FinalVideo.Stop();
FileWriter.Close();
//this.AVIwriter.Close();
pictureBox1.Image = null;
}
}
private void button3_Click(object sender, EventArgs e)
{
pictureBox1.Image.Save("IMG" + DateTime.Now.ToString("hhmmss") + ".jpg");
}
private void button4_Click(object sender, EventArgs e)
{
this.Close();
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
if (FinalVideo == null)
{ return; }
if (FinalVideo.IsRunning)
{
this.FinalVideo.Stop();
FileWriter.Close();
//this.AVIwriter.Close();
}
}
}
}

Categories

Resources