Can you help me CopyFileDialog windows form - c#

Hello I have created a program that contains a btnCopy associated with a copyfiledialog, I would like to know why when I press the btnCopy it copies me several files at the same time, I would like that it copies the files one after the other, can will you help me?
private void btnCopy_Click(object sender,EventArgs e)
{
string sourceDir = #"C:\Users\PORTABLEHP\Documents";
string destDir = #"C:\Users\PORTABLEHP\Documents\xgen";
try
{
string [] txtList = Directory.GetFiles(sourceDir,"*.txt");
foreach (string f in txtList)
{
try
{
string fName = f.Substring(sourceDir.Length + 1);
string [] files = new string[sourceDir.Length];
progressBar1.Value = 1;
progressBar1.Minimum = 0;
progressBar1.Maximum = files.Length;
for(int i = 1;i < files.Length; i++)
{
progressBar1.PerformStep();
File.Copy(Path.Combine(sourceDir,fName),
Path.Combine(destDir,fName), true);
}
}
catch(IOException copyerror)
{
MessageBox.Show(copyerror.Message)
}
,

Try this:
using System;
using System.IO;
using System.Windows.Forms;
using Microsoft.VisualBasic.FileIO;
public partial class Form1 : Form
{
// other code
private void button1_Click(object sender, EventArgs e)
{
string sourceDir = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
string destDir = Path.Combine(sourceDir, "xgen");
string[] txtList =
Directory.GetFiles(sourceDir, "*.txt");
progressBar1.Value = 1;
progressBar1.Minimum = 0;
progressBar1.Maximum = txtList.Length;
try
{
foreach (string f in txtList)
{
string fName = Path.GetFileName(f); //f.Substring(sourceDir.Length + 1);
string destFile = Path.Combine(destDir, fName);
FileSystem.CopyFile(
f, destFile, UIOption.AllDialogs, UICancelOption.ThrowException);
progressBar1.PerformStep();
}
}
catch (IOException copyerror)
{
MessageBox.Show(copyerror.Message);
}
}
}
Note that you need to add a reference to Microsoft.VisualBasic to gain access to FileSystem.CopyFile() which copies with the standard windows UI.

Related

How can I compare 2 images and delete the last one if they are the same?

I made a video recorder that takes screenshots each frame and saves it in a temporary folder. When I press the Stop recording button it puts it all together in one video. I now need to have my program check the latest 2 screenshots it has taken and compare them to find changes, if change wasn't found the last image should get deleted. In the other hand if the 2 images had any difference, both images would stay there.
Thank you for helping me out!
Forms1.cs[Design]
Below is my Screen Recorder script
ScreenRecorder.cs
using System.IO;
using System.Drawing;
using System.Diagnostics;
using System.Drawing.Imaging;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using Accord.Video;
using Accord.Video.FFMPEG;
using GroupDocs.Comparison.Options;
using GroupDocs.Comparison;
namespace Timelapser_version_1._2
{
class ScreenRecorder
{
//Video variables:
private Rectangle bounds;
private string outputPath = "";
private string tempPath = "";
private int fileCount = 1;
private List<string> inputImageSequence = new List<string>();
//File variables:
private string audioName = "mic.wav";
private string videoName = "video.mp4";
private string finalName = "FinalVideo.mp4";
//Time variable:
Stopwatch watch = new Stopwatch();
//Audio variables:
public static class NativeMethods
{
[DllImport("winmm.dll", EntryPoint = "mciSendStringA", ExactSpelling = true, CharSet = CharSet.Ansi, SetLastError = true)]
public static extern int record(string lpstrCommand, string lpstrReturnString, int uReturnLength, int hwndCallback);
}
//ScreenRecorder Object:
public ScreenRecorder(Rectangle b, string outPath)
{
//Create temporary folder for screenshots:
CreateTempFolder("tempScreenCaps");
//Set variables:
bounds = b;
outputPath = outPath;
}
//Create temporary folder:
private void CreateTempFolder(string name)
{
//Check if a C or D drive exists:
if (Directory.Exists("D://"))
{
string pathName = $"D://{name}";
Directory.CreateDirectory(pathName);
tempPath = pathName;
}
else
{
string pathName = $"C://Documents//{name}";
Directory.CreateDirectory(pathName);
tempPath = pathName;
}
}
//Change final video name:
public void setVideoName(string name)
{
finalName = name;
}
//Delete all files and directory:
private void DeletePath(string targetDir)
{
string[] files = Directory.GetFiles(targetDir);
string[] dirs = Directory.GetDirectories(targetDir);
//Delete each file:
foreach (string file in files)
{
File.SetAttributes(file, FileAttributes.Normal);
File.Delete(file);
}
//Delete the path:
foreach (string dir in dirs)
{
DeletePath(dir);
}
Directory.Delete(targetDir, false);
}
//Delete all files except the one specified:
private void DeleteFilesExcept(string targetDir, string excDir)
{
string[] files = Directory.GetFiles(targetDir);
//Delete each file except specified:
foreach (string file in files)
{
if (file != excDir)
{
File.SetAttributes(file, FileAttributes.Normal);
File.Delete(file);
}
}
}
//Clean up program on crash:
public void cleanUp()
{
if (Directory.Exists(tempPath))
{
DeletePath(tempPath);
}
}
//Return elapsed time:
public string getElapsed()
{
return string.Format("{0:D2}:{1:D2}:{2:D2}", watch.Elapsed.Hours, watch.Elapsed.Minutes, watch.Elapsed.Seconds);
}
//Record video:
public void RecordVideo()
{
//Keep track of time:
watch.Start();
int blac=0;
string a ="screenshot-1+%d";
using (Bitmap bitmap = new Bitmap(bounds.Width, bounds.Height))
{
using (Graphics g = Graphics.FromImage(bitmap))
{
//Add screen to bitmap:
g.CopyFromScreen(new Point(bounds.Left, bounds.Top), Point.Empty, bounds.Size);
}
//Save screenshot:
string name = tempPath + "//screenshot-" + fileCount + ".png";
bitmap.Save(name, ImageFormat.Png);
inputImageSequence.Add(name);
fileCount++;
//Dispose of bitmap:
bitmap.Dispose();
}
}
//Record audio:
public void RecordAudio()
{
NativeMethods.record("open new Type waveaudio Alias recsound", "", 0, 0);
NativeMethods.record("record recsound", "", 0, 0);
}
//Save audio file:
private void SaveAudio()
{
string audioPath = "save recsound " + outputPath + "//" + audioName;
NativeMethods.record(audioPath, "", 0, 0);
NativeMethods.record("close recsound", "", 0, 0);
}
//Save video file:
public void SaveVideo(int width, int height, int frameRate)
{
using (VideoFileWriter vFWriter = new VideoFileWriter())
{
vFWriter.Open(outputPath + "//"+ videoName, width, height, frameRate, VideoCodec.MPEG4);
//Make each screenshot into a video frame:
foreach (string imageLocation in inputImageSequence)
{
Bitmap imageFrame = System.Drawing.Image.FromFile(imageLocation) as Bitmap;
vFWriter.WriteVideoFrame(imageFrame);
imageFrame.Dispose();
}
//Close:
vFWriter.Close();
}
}
//Combine video and audio files:
private void CombineVideoAndAudio(string video, string audio)
{
//FFMPEG command to combine video and audio:
string args = $"/c ffmpeg -i \"{video}\" -i \"{audio}\" -shortest {finalName}";
ProcessStartInfo startInfo = new ProcessStartInfo
{
CreateNoWindow = false,
FileName = "cmd.exe",
WorkingDirectory = outputPath,
Arguments = args
};
//Execute command:
using (Process exeProcess = Process.Start(startInfo))
{
exeProcess.WaitForExit();
}
}
public void Stop()
{
//Stop watch:
watch.Stop();
//Video variables:
int width = bounds.Width;
int height = bounds.Height;
int frameRate = 10;
//Save audio:
SaveAudio();
//Save video:
SaveVideo(width, height, frameRate);
//Combine audio and video files:
CombineVideoAndAudio(videoName, audioName);
//Delete the screenshots and temporary folder:
DeletePath(tempPath);
//Delete separated video and audio files:
DeleteFilesExcept(outputPath, outputPath + "\\" + finalName);
}
}
}
forms1.cs
using System;
using System.Drawing;
using System.Windows.Forms;
namespace Timelapser_version_1._2
{
public partial class Timelapser : Form
{
string outputPath = "";
bool folderSelected = false;
string finalVidName = "FinalVideo.mp4";
// Screen recorder object:
ScreenRecorder screenRec = new ScreenRecorder(new Rectangle(), " ");
public Timelapser()
{
InitializeComponent();
}
private void Start_Click(object sender, EventArgs e)
{
bool containsMP4 = finalVidName.Contains(".mp4");
if (folderSelected && containsMP4)
{
screenRec.setVideoName(finalVidName);
timer1.Start();
}
else if(!folderSelected && containsMP4)
{
MessageBox.Show("You must select an output Folder before recording","Error");
}
else if (folderSelected && !containsMP4)
{
MessageBox.Show("You must select video name that ends in '.mp4'", "Error");
finalVidName = "FinalVideo.mp4";
}
}
private void Stop_Click(object sender, EventArgs e)
{
timer1.Stop();
screenRec.Stop();
Application.Restart();
}
private void timer1_Tick(object sender, EventArgs e)
{
screenRec.RecordVideo();
screenRec.RecordAudio();
Timelabel.Text = screenRec.getElapsed();
}
private void SelectFolder_Click(object sender, EventArgs e)
{
FolderBrowserDialog folderBrowser = new FolderBrowserDialog();
folderBrowser.Description = "Select an Output Folder";
if (folderBrowser.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
outputPath = #folderBrowser.SelectedPath;
folderSelected = true;
Rectangle bounds = Screen.FromControl(this).Bounds;
screenRec = new ScreenRecorder(bounds,outputPath);
}
else
{
MessageBox.Show("Please select a folder");
}
}
I found the solution, to be able to check each 2 screenshots we need the function below.
public static List<bool> GetHash(Bitmap bmpSource)
{
List<bool> lResult = new List<bool>();
//create new image with 128x128 pixel
Bitmap bmpMin = new Bitmap(bmpSource, new System.Drawing.Size(128, 128));
for (int j = 0; j < bmpMin.Height; j++)
{
for (int i = 0; i < bmpMin.Width; i++)
{
//reduce colors to true / false
lResult.Add(bmpMin.GetPixel(i, j).GetBrightness() < 0.1f);
}
}
return lResult;
}
This function gets the screenshots and creates a 128x128 version of them. Also it changes the colour to black and white to get a true or false.
Then we need to call the function for each 2 screenshots as shown below.
List<bool> iHash1 = GetHash(new Bitmap(tempPath + "//screenshot-" + k + ".png"));
List<bool> iHash2 = GetHash(new Bitmap(tempPath + "//screenshot-" + (k + 1) + ".png"));
//determine the number of equal pixel (x of 256)
long equalElements = iHash1.Zip(iHash2, (i, j) => i == j).Count(eq => eq);
Debug.Write(equalElements);
if (equalElements > 16300 )
{
var filePath = tempPath + "//screenshot-" + (k+1) + ".png";
File.Delete(filePath);
}

c# Progressbar, Overflow returns negative value

I'm creating a backup application. I have 5 folders in different locations what needs to be copied to one backup folder. (solved via checkbox.checked)
The main issue is that some of the folders are more than 3-4GB in total (with all subfolders) Progressbar is not updated because "maxbyte" returns a negative value. (I assume int32 overflows after 2gb file copy)
(Sorry can't explain it more in details..I'm just a beginner C# programmer)
using System;
using System.ComponentModel;
using System.Linq;
using System.Windows.Forms;
using System.IO;
using memoQClientBackuTool;
namespace memoQBackupTool
{
public partial class BGWorker : Form
{
public BGWorker()
{
InitializeComponent();
}
BackgroundWorker bw;
string source = "";
string target = "";
bool isfile = false;
int filecount = 0;
int currentFileNr = 1;
string newFilename = "";
int maxbytes = 0;
public void ShowProgress(string from, string to, bool isf)
{
InitializeComponent();
source = from;
target = to;
isfile = isf;
bw = new BackgroundWorker();
bw.DoWork += new DoWorkEventHandler(bw_DoWork);
bw.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bw_RunWorkerCompleted);
bw.ProgressChanged += new ProgressChangedEventHandler(bw_ProgressChanged);
bw.WorkerReportsProgress = true;
bw.WorkerSupportsCancellation = true;
GetFileData();
}
private void GetFileData()
{
if (isfile)
{
FileInfo fi = new FileInfo(source);
maxbytes = Convert.ToInt32(fi.Length);
//
//set progress bar length
//
progressBar1.Minimum = 0;
progressBar2.Minimum = 0;
progressBar1.Maximum = maxbytes;
progressBar2.Maximum = 1;
bw.RunWorkerAsync();
}
else
{
GetDirectoryInfo(source);
//
//set progress bar length
//
progressBar1.Minimum = 0;
progressBar2.Minimum = 0;
progressBar1.Maximum = maxbytes;
progressBar2.Maximum = filecount;
bw.RunWorkerAsync();
}
}
private void GetDirectoryInfo(string source)
{
string[] files = Directory.GetFiles(source);
foreach (string file in files)
{
FileInfo fi = new FileInfo(file);
maxbytes += Convert.ToInt32(fi.Length);
filecount += 1;
}
string[] folders = Directory.GetDirectories(source);
foreach (string folder in folders)
{
GetDirectoryInfo(folder);
}
}
void bw_DoWork(object sender, DoWorkEventArgs e)
{
if (isfile)
{
FileStream fs = new FileStream(source, FileMode.Open);
long FileSize = fs.Length;
FileInfo fi = new FileInfo(source);
byte[] bBuffer = new byte[(int)FileSize];
fs.Read(bBuffer, 0, (int)FileSize);
fs.Close();
UpdateLabels(fi.FullName);
newFilename = fi.Name;
try
{
FileStream fss = new FileStream(target + "\\" + newFilename, FileMode.CreateNew);
BinaryWriter biwr = new BinaryWriter(fss);
for (int i = 0; i < bBuffer.Length; i += 15000)
{
if (i + 15000 < bBuffer.Length)
{
biwr.Write(bBuffer, i, 15000);
bw.ReportProgress(15000);
}
else
{
biwr.Write(bBuffer, i, bBuffer.Length - i);
bw.ReportProgress(bBuffer.Length - i);
}
}
biwr.Close();
fss.Close();
} catch (IOException){
MessageBox.Show("Nincs olyan...");
}
}
else
{
string[] temp = source.Split('\\');
target += "\\" + temp[temp.Count() - 1];
DirectoryInfo s = new DirectoryInfo(source);
DirectoryInfo t = new DirectoryInfo(target);
CopyDirectory(s, t);
}
if (bw.CancellationPending)
{
e.Cancel = true;
return;
}
}
public void CopyDirectory(DirectoryInfo di_source, DirectoryInfo di_target)
{
if (Directory.Exists(di_target.FullName) == false)
{
Directory.CreateDirectory(di_target.FullName);
}
foreach (FileInfo fi in di_source.GetFiles())
{
newFilename = fi.Name;
FileStream fs = new FileStream(fi.FullName, FileMode.Open);
long FileSize = fs.Length;
byte[] bBuffer = new byte[(int)FileSize];
fs.Read(bBuffer, 0, (int)FileSize);
fs.Close();
UpdateLabels(fi.FullName);
if (File.Exists(di_target.ToString() + "\\" + fi.Name))
{
Random rand = new Random();
newFilename = newFilename + "_" + rand.Next(1, 10000);
}
FileStream fss = new FileStream(di_target.ToString() + "\\" + newFilename, FileMode.CreateNew);
BinaryWriter biwr = new BinaryWriter(fss);
for (int i = 0; i < bBuffer.Length; i += 500000)
{
if (i + 500000 < bBuffer.Length)
{
biwr.Write(bBuffer, i, 500000);
bw.ReportProgress(500000);
}
else
{
biwr.Write(bBuffer, i, bBuffer.Length - i);
bw.ReportProgress(bBuffer.Length - i);
}
}
biwr.Close();
fss.Close();
}
foreach (DirectoryInfo di_SourceSubDir in di_source.GetDirectories())
{
DirectoryInfo nextSubDir = di_target.CreateSubdirectory(di_SourceSubDir.Name);
CopyDirectory(di_SourceSubDir, nextSubDir);
}
}
void bw_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
progressBar1.Value += e.ProgressPercentage;
int copied = progressBar1.Value / 1024;
int total = maxbytes / 1024;
lbl_kbscopied.Text = copied + "/" + total;
}
delegate void UpdateLabelsDelegate(string filename);
void UpdateLabels(string fname)
{
if (!InvokeRequired)
{
lbl_filename.Text = "Copying: " + fname;
lbl_filenr.Text = "File: " + currentFileNr + "/" + filecount;
currentFileNr++;
progressBar2.Value += 1;
}
else
{
Invoke(new UpdateLabelsDelegate(UpdateLabels), new object[] { fname });
}
}
private void button1_Click(object sender, EventArgs e)
{
Cursor.Current = Cursors.WaitCursor;
bw.CancelAsync();
}
private void bw_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
if (e.Cancelled)
{
Cursor.Current = Cursors.Default;
CustomMsgBox.Show("The task has been canceled", "Error", "OK");
this.Close();
}
else if (e.Error != null)
{
MessageBox.Show("Error. Details: " + (e.Error as Exception).ToString());
}
else
{
this.Close();
}
}
}
}
Report progress not in absolute values, but in relative; percentage, for example.
Let say that 1MB file is 100% of progress bar. That means that you have to initialize it with 100: progressBar1.Maximum = 100. Then every 15000 bytes that were copied is a little bit more than 1%. Instead of bw.ReportProgress(15000) do bw.ReportProgress(1).
I will suggest to use long instead of int wherever you are getting total bytes copied/uploaded so far. If I understood your code you are using int in for loop where you call ReportProgress

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

A generic error occurred in GDI+ ExternalException Was caught cant figure out why

The error is on the line:
for (int x = 0; x < myList.Count(); x++)
The x++is painted with green.
Im using backgroundoworker and I used this code same code in another form before without a backgroundworker and it worked good. Now in the other form im using a click button event to show() this form and I want to use a progressBar1 to show the progress of the backgroundowrker work.
I used now try and catch inside this for loop and it went to the catch point and showed me the error. The full exception message is:
at System.Drawing.Image.Save(String filename, ImageCodecInfo encoder, EncoderParameters encoderParams)
at System.Drawing.Image.Save(String filename, ImageFormat format)
at mws.Animation_Radar_Preview.backGroundWorker1_DoWork(Object sender, DoWorkEventArgs e) in D:\C-Sharp\Download File\Downloading-File-Project-Version-012\Downloading File\Animation_Radar_Preview.cs:line 163
gifImages isnt null.
This is the full code of this form:
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.IO;
using DannyGeneral;
using unfreez_wrapper;
namespace mws
{
public partial class Animation_Radar_Preview : Form
{
int mtpStart;
int mtpEnd;
Picturebox1_Fullscreen pb1;
string radar_images_download_directory;
string tempRadarPngToGifDirectory;
int numberOfFiles;
UnFreezWrapper unfreez;
string path_exe;
List<string> myList;
string previewDirectory;
int animatedGifSpeed;
bool loop;
string nameOfStartFile;
string nameOfEndFile;
string previewFileName;
BackgroundWorker backGroundWorker1;
Image img;
private MemoryStream _memSt = null;
public Animation_Radar_Preview()
{
InitializeComponent();
mtpStart = Picturebox1_Fullscreen.mtp1Start;
mtpEnd = Picturebox1_Fullscreen.mtp1End;
animatedGifSpeed = Picturebox1_Fullscreen.animatedSpeed;
loop = Picturebox1_Fullscreen.looping;
pb1 = new Picturebox1_Fullscreen();
radar_images_download_directory = Options_DB.Get_Radar_Images_Download_Directory();
path_exe = Path.GetDirectoryName(Application.LocalUserAppDataPath);
tempRadarPngToGifDirectory = path_exe + "\\" + "tempRadarPngToGifDirectory";
if (Directory.Exists(tempRadarPngToGifDirectory))
{
}
else
{
Directory.CreateDirectory(tempRadarPngToGifDirectory);
}
previewDirectory = path_exe + "\\" + "previewDirectory";
if (Directory.Exists(previewDirectory))
{
}
else
{
Directory.CreateDirectory(previewDirectory);
}
previewFileName = previewDirectory + "\\" + "preview.gif";
loop = false;
animatedGifSpeed = 0;
unfreez = new UnFreezWrapper();
backGroundWorker1 = new BackgroundWorker();
backGroundWorker1.WorkerSupportsCancellation = true;
this.backGroundWorker1.WorkerReportsProgress = true;
backGroundWorker1.ProgressChanged += new ProgressChangedEventHandler(backGroundWorker1_ProgressChanged);
backGroundWorker1.DoWork += new DoWorkEventHandler(backGroundWorker1_DoWork);
backGroundWorker1.RunWorkerCompleted += new RunWorkerCompletedEventHandler(backGroundWorker1_RunWorkerCompleted);
backGroundWorker1.RunWorkerAsync();
progressBar1.Value = 0;
}
private void button2_Click(object sender, EventArgs e)
{
DialogResult result1;
result1 = new DialogResult();
SaveFileDialog sd = new SaveFileDialog();
sd.Title = "Select a folder to save the animated gif to";
sd.InitialDirectory = "c:\\";
sd.FileName = null;
sd.Filter = "Gif File|*.gif;*.jpg|Gif|*.gif";
sd.FilterIndex = 1;
sd.RestoreDirectory = true;
result1 = sd.ShowDialog();
string file1 = sd.FileName;
if (result1 == DialogResult.OK)
{
File.Move(previewFileName, file1);
}
}
public void pictureBoxImage(string pbImage)
{
Image img2 = null;
try
{
using (img = Image.FromFile(pbImage))
{
//get the old image thats loaded from the _memSt memorystream
//and dispose it
Image i = this.pictureBox1.Image;
this.pictureBox1.Image = null;
if (i != null)
i.Dispose();
//grab the old stream
MemoryStream m = _memSt;
//save the new image to this stream
_memSt = new MemoryStream();
img.Save(_memSt, System.Drawing.Imaging.ImageFormat.Gif);
if (m != null)
m.Dispose();
//create our image to display
img2 = Image.FromStream(_memSt);
}
if (img2 != null)
pictureBox1.Image = img2;
label2.Text = numberOfFiles.ToString();
label6.Text = nameOfStartFile.ToString();
label4.Text = nameOfEndFile.ToString();
//File.Delete(pbImage);
}
catch(Exception err)
{
Logger.Write("Animation Error >>> " + err);
}
}
private void backGroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
progressBar1.Value = e.ProgressPercentage;
}
private void backGroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
List<string> myGifList;
Image gifImages = null;
//button1.Enabled = false;
Animation_Radar_Preview ap = new Animation_Radar_Preview();
//ap.FormClosing += new FormClosingEventHandler(ap_FormClosing);
FileInfo[] fi;
DirectoryInfo dir1 = new DirectoryInfo(radar_images_download_directory);
fi = dir1.GetFiles("*.png");
myList = new List<string>();
myGifList = new List<string>();
for (int i = mtpStart; i < mtpEnd; i++)
{
myList.Add(fi[i].FullName);
}
for (int x = 0; x < myList.Count(); x++)
{
try
{
gifImages = Image.FromFile(myList[x]);
gifImages.Save(tempRadarPngToGifDirectory + "\\" + x.ToString("D6") + ".Gif", System.Drawing.Imaging.ImageFormat.Gif);
}
catch (Exception ex)
{
MessageBox.Show(x.ToString() + "\r\n" + (gifImages == null).ToString() + "\r\n" + ex.Message);
}
}
myGifList = new List<string>();
dir1 = new DirectoryInfo(tempRadarPngToGifDirectory);
fi = dir1.GetFiles("*.gif");
nameOfStartFile = fi[0].Name;
for (int i = 0; i < fi.Length; i++)
{
myGifList.Add(fi[i].FullName);
//backGroundWorker1.ReportProgress(i);
nameOfEndFile = fi[i].Name.Length.ToString();
}
numberOfFiles = myGifList.Count();
unfreez.MakeGIF(myGifList, previewFileName, animatedGifSpeed, loop);
/*this.Invoke((MethodInvoker)delegate
{
pictureBoxImage(previewFileName);
});*/
}
private void backGroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
pictureBoxImage(previewFileName);
}
}
}
I'm not entirely sure what is going wrong, especially as you say this same code worked previously — but it is not clear whether it worked with the same set of images.
Anyhow, the documentation for the Save method says that an ExternalException will be thrown in one of two situations:
Image was saved with the wrong format.
Image is saved to the file it was created from.
It cannot be that you are saving over the file because you are changing its extension, so it must be the wrong format. What this actually means is not clear. Perhaps one of the source images is using capabilities of the PNG format that cannot be converted to GIF, e.g. alpha channel transparency.
If I may take a moment to make some other suggestions too:
if (Directory.Exists(tempRadarPngToGifDirectory))
{
}
else
{
Directory.CreateDirectory(tempRadarPngToGifDirectory);
}
The empty 'success' case is not required if you invert the logic:
if (!Directory.Exists(tempRadarPngToGifDirectory)
{
Directory.CreateDirectory(tempRadarPngToGifDirectory);
}
Code that manipulates file paths such as the following:
tempRadarPngToGifDirectory = path_exe + "\\" + "tempRadarPngToGifDirectory";
You should consider using the Path class as this will handle the edge cases better and make more portable code:
tempRadarPngToGifDirectory = Path.Combine(path_exe, "tempRadarPngToGifDirectory");

How to build a wordlist

So now I want to make Estonian wordlist ~about 20m unique words in lowercase. To get input for wordlist, corpus of Estonian can be used. Corpus files are in Text Encoding Initiative (TEI) format. I tried using regex to find the words.
This is what I made: it's inefficient, mcv is all messed up, it brakes if hashset of words can't fit in memory, it's not aware of inputs encoding - so probably letters like š make problems, it does not show estimated completion time, some controls have default names and some don't, it does not use multitasking (not sure if it should), it uses some weird fixes and lots of locking interface so that it would appear not 'frozen'. At least its so short, that you hardly notice there are no comments.
Upside is, that it can almost read words without many mistakes, from .tei, .txt, .csv, smgl, xhtml or any a like format inputs.
Now you know what I want to do, how I have tried doing it (with what problems), and again I'm just trying to find out how to do it (with minimal manual labor).
Image example:
Code example & Gui:
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.Data.SqlClient;
using System.IO;
using System.Text.RegularExpressions;
namespace Reader
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void listView1_DragEnter(object sender, DragEventArgs e)
{
if (e.Data.GetDataPresent(DataFormats.FileDrop, false) == true)
{
e.Effect = DragDropEffects.All;
}
}
private void listView1_DragDrop(object sender, DragEventArgs e)
{
setguiLock(true);
this.loading.Visible = true;
ignorechecking = true;
string[] files = (string[])e.Data.GetData(DataFormats.FileDrop, false);
Dictionary<String, ListViewGroup> listviewgroups = new Dictionary<string,ListViewGroup>();
int filenamesi = 0;
foreach (string file in files)
{
progresslabel.Text = string.Format("Progress: \t[ {0} / {1} ]", filenamesi++, files.Length);
Application.DoEvents();
if (File.Exists(file))
{
FileInfo ff = new System.IO.FileInfo(file);
if (!listviewgroups.ContainsKey(ff.DirectoryName))
{
listviewgroups.Add(ff.DirectoryName, new ListViewGroup(ff.DirectoryName, HorizontalAlignment.Left));
listView1.Groups.Add(listviewgroups[ff.DirectoryName]);
}
ListViewItem item = new ListViewItem(ff.Name);
listviewgroups[ff.DirectoryName].Items.Add(item);
item.Checked = true;
item.SubItems.Add("" +((int)ff.Length/1024)+" KB");
// item.Group.Header = ff.DirectoryName;
// listviewgroups[ff.DirectoryName].Items.Add(item);
listView1.Items.Add(item);
}
}
setguiLock(false);
ignorechecking = false;
this.loading.Visible = false;
updatechecked();
}
private void listView1_ItemChecked(object sender, ItemCheckedEventArgs e)
{
updatechecked();
}
private bool ignorechecking = false;
private void updatechecked(){
if (ignorechecking)
return;
long size = 0;
int count = 0;
foreach (ListViewItem item in this.listView1.Items)
{
if (item.Checked)
{
count++;
size += Int32.Parse(item.SubItems[1].Text.Split(" ".ToArray())[0]);
}
}
this.text1.Text = ""+count;
this.text2.Text = ""+size + " KB";
}
private void putHashset(HashSet<string> d, string filename)
{
StringBuilder sb = new StringBuilder();
foreach (string key in d)
sb.Append(key).Append("\n");
File.WriteAllText(filename, sb.ToString());
}
private HashSet<string> getHashset(string filename)
{
return new HashSet<string>(new Regex("\\n+").Split(File.ReadAllText(filename)));
}
private void removefilefromlistview(string fullfilename) {
foreach (ListViewItem item in this.listView1.Items)
{
String file = item.Group.Header + "\\" + item.SubItems[0].Text;
if (fullfilename.CompareTo(file) == 0)
{
item.Checked = false;
this.listView1.Items.Remove(item);
}
}
}
private void starter(object sender, EventArgs e)
{
HashSet<string> filenames = new HashSet<string>();
StringBuilder data = null;
setguiLock(true);
this.time2.Text = "";
this.time1.Text = String.Format("{0:d/M/yyyy HH:mm:ss}", DateTime.Now);
foreach (ListViewItem item in this.listView1.Items) {
if (item.Checked) {
String file = item.Group.Header + "\\" + item.SubItems[0].Text;
if (File.Exists(file))
filenames.Add(file);
}
}
string outputfile = output.Text;
HashSet<string> words = null;
if (File.Exists(output.Text))
words = getHashset(outputfile);
else
words = new HashSet<string>();
int filenamesnr = filenames.Count;
int filenamesi = 0;
foreach (String str in filenames){
progresslabel.Text = string.Format("Progress: \t[ {0} / {1} ]", filenamesi++, filenamesnr);
Application.DoEvents();
data = new StringBuilder(System.IO.File.ReadAllText(str, Encoding.UTF7).ToLower());
data = data.Replace("ä", "ä");
data = data.Replace("ö", "ö");
data = data.Replace("ü", "ü");
data = data.Replace("õ", "õ");
String sdata = new Regex(#"<(.|\n)*?>|%[a-zA-Z0-9]+?;|&[#a-zA-Z0-9]+?;").Replace(data.ToString(), "");
foreach (string word in new Regex("[^A-Za-zšžõäöüŠŽÕÄÖÜ]+").Split(sdata))
if(word.Length>1)
words.Add(word);
removefilefromlistview(str);
}
progresslabel.Text = "Progress:";
putHashset(words, outputfile);
foreach (ListViewItem item in this.listView1.Items)
if (item.Checked)
{
item.Checked = false;
listView1.Items.Remove(item);
}
this.time2.Text = String.Format("{0:d/M/yyyy HH:mm:ss}", DateTime.Now);
setguiLock(false);
}
private void setguiLock(bool value){
if(value){
this.Enabled = false;
this.button1.Enabled = false;
this.listView1.Enabled = false;
this.output.Enabled = false;
this.openoutput.Enabled = false;
this.progresslabel.Visible = true;
this.Enabled = true;
}else{
this.Enabled = false;
this.openoutput.Enabled = true;
this.output.Enabled = true;
this.listView1.Enabled = true;
this.button1.Enabled = true;
this.progresslabel.Visible = false;
this.Enabled = true;
}
}
private void button2_Click(object sender, EventArgs e)
{
if (!File.Exists(output.Text))
File.WriteAllText(output.Text, " ");
System.Diagnostics.Process.Start(output.Text);
}
}
}
You need to get the right tool for the job. The quantity of data and markup in a linguistic corpus like this means you need a proper XML-aware indexing solution. Examples include eXist, XAIRA, CQP...

Categories

Resources