I wrote a simple image uploader in C#. Here's my code:
using System;
using System.Collections.Specialized;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Net;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Xml.Linq;
namespace Snappx
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
GlobalHook.HookManager.KeyUp += new KeyEventHandler(MyKeyUp);
CheckForIllegalCrossThreadCalls = false;
new Task(this.Hide).Start();
}
private void exitToolStripMenuItem_Click(object sender, EventArgs e)
{
Environment.Exit(-1);
}
string ORIGINIM;
async void MyKeyUp(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.PrintScreen)
{
await GetImage();
e.Handled = true;
}
else e.Handled = false;
}
String img = #"temp";
async Task GetImage()
{
Rectangle bounds = Screen.GetBounds(Point.Empty);
using (Bitmap bitmap = new Bitmap(bounds.Width, bounds.Height))
{
using (Graphics g = Graphics.FromImage(bitmap))
{
g.CopyFromScreen(Point.Empty, Point.Empty, bounds.Size);
}
bitmap.Save(img, ImageFormat.Png);
}
using (var w = new WebClient())
{
var values = new NameValueCollection { { "key", "85684005b7d4faa4c33ee480010d4982" }, { "image", Convert.ToBase64String(File.ReadAllBytes(img)) } };
notifyIcon1.ShowBalloonTip(3, "Uploading", "Uploading image to Imgur", ToolTipIcon.Info);
w.UploadProgressChanged += new UploadProgressChangedEventHandler(wc_UploadProgressChanged);
Task<byte[]> x = w.UploadValuesTaskAsync(new Uri("http://imgur.com/api/upload.xml"), values);
byte[] response = await x;
while (w.IsBusy) System.Threading.Thread.Sleep(500);
File.Delete(img);
ORIGINIM = Convert.ToString(XDocument.Load(new MemoryStream(response)));
ORIGINIM = ORIGINIM.Substring(ORIGINIM.LastIndexOf("<original_image>")).Replace("<original_image>", "");
ORIGINIM = ORIGINIM.Substring(0, ORIGINIM.LastIndexOf("</original_image>")).Replace("</original_image>", "");
Clipboard.SetText(ORIGINIM);
if (!File.Exists(#"Uploads.txt")) File.Create(#"Uploads.txt");
new StreamWriter(#"Uploads.txt").WriteLine(ORIGINIM);
notifyIcon1.ShowBalloonTip(3, "Done", "URL copied to clipboard.", ToolTipIcon.Info);
}
}
private void wc_UploadProgressChanged(object sender, UploadProgressChangedEventArgs e)
{
int percentage = e.ProgressPercentage * 2;
notifyIcon1.ShowBalloonTip(3, "Uploading", (percentage).ToString() + "%", ToolTipIcon.Info);
}
}
}
First of all, when there is no Uploads.txt file, it returns an Exception handler. Then second time I run it, it creates it. Is there any simpler way to store it?
Second question:
Am I able to add two different options, one for capture full screen and one for select screen region.
How could I integrate it with my code? Could you post it?
Instead of (!File.Exists(#"Uploads.txt")) File.Create(#"Uploads.txt") try this
using (StreamWriter sw = new StreamWriter(File.Open(#"Uploads.txt", FileMode.OpenOrCreate)))
{
sw.WriteLine(ORIGINIM);
}
The reason why it worked on the second try is because you didn't create a lock on the file with File.Create - the existing logic opens the file, which creates a FileStream, then you attempt to open StreamWriter on the same file. You should instead create the StreamWriter by passing the FileStream into its constructor, as shown in the above example.
Related
I made a application with iTextSharp to put numbers on a PDF file.
As you will see in the following code, my application just can do this, only if the file is in a specific directory.
So I made an "Other" button where the user can select a file.
What I want to do now is, that the chosen file will download the converted PDF.
Code:
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 iTextSharp.text;
using iTextSharp.text.pdf;
namespace NummerierePDF
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
byte[] bytes = File.ReadAllBytes(#"L:\Users\user\Documents\PDFnummerieren\PDF.pdf");
iTextSharp.text.Font blackFont = FontFactory.GetFont("Arial", 12, iTextSharp.text.Font.NORMAL, BaseColor.BLACK);
using (MemoryStream stream = new MemoryStream())
{
PdfReader reader = new PdfReader(bytes);
using (PdfStamper stamper = new PdfStamper(reader, stream))
{
int pages = reader.NumberOfPages;
for (int i = 1; i <= pages; i++)
{
ColumnText.ShowTextAligned(stamper.GetOverContent(i), Element.ALIGN_RIGHT, new Phrase(i.ToString(), blackFont), 568f, 15f, 0);
}
}
bytes = stream.ToArray();
}
File.WriteAllBytes(#"L:\Users\user\Documents\PDFnummerieren\PDF1.pdf", bytes);
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void button2_Click(object sender, EventArgs e)
{
this.Close();
}
private void button3_Click(object sender, EventArgs e)
{
var FD = new System.Windows.Forms.OpenFileDialog();
if (FD.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
string fileToOpen = FD.FileName;
System.IO.FileInfo File = new System.IO.FileInfo(FD.FileName);
System.IO.StreamReader reader = new System.IO.StreamReader(fileToOpen);
}
}
}
}
So File.WriteAllBytes(#"L:\Users\user\Documents\PDFnummerieren\PDF1.pdf", bytes);
can stay because it doesn't matter where the file will be downloaded after it's converted.
But File.ReadAllBytes(#"L:\Users\user\Documents\PDFnummerieren\PDF.pdf");
shouldn't be a specific directory, it should get the chosen file from button3.
As you probably noticed I'm new into programming so I thought maybe I could do this: File.ReadAllBytes(fileToOpen);
to get the string. Though that doesn't do his job.
Thanks for your time.
If you want to use a variable between methods of the same class then you need to declare a private and non-static class level variable (called also Instance Field). This is visible to every method of the class.
public partial class Form1 : Form
{
// Here declare a variable visible to all methods inside the class but
// not outside the class. Init it with an empty string
private string theFile = "";
private void button1_Click(object sender, EventArgs e)
{
// When you click the button1 check if the variable
// has been set to something in the button3 click event handler
if(string.IsNullOrEmpty(theFile) || !File.Exists(theFile))
return;
// Now you can use it to load the file and continue with the code
// you have already written
byte[] bytes = File.ReadAllBytes(theFile);
......
......
}
private void button3_Click(object sender, EventArgs e)
{
// The only job of button3 is to select the file to work on
// as you can see we can use the variable also here
var FD = new System.Windows.Forms.OpenFileDialog();
if (FD.ShowDialog() == System.Windows.Forms.DialogResult.OK)
theFile = FD.FileName;
}
}
But do you really need a separate button for this? I mean you could put the three lines of code in the button3 directly in at the start of the code in button1 and remove the superfluos (at this point) button3
I suggest you to read some docs on variable's Scope and Lifetime
Try this
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 iTextSharp.text;
using iTextSharp.text.pdf;
namespace NummerierePDF
{
public partial class Form1 : Form
{
string fileToOpen = string.Empty;
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
if(string.IsNullOrWhiteSpace(fileToOpen)) return;
byte[] bytes = File.ReadAllBytes(fileToOpen);
iTextSharp.text.Font blackFont = FontFactory.GetFont("Arial", 12, iTextSharp.text.Font.NORMAL, BaseColor.BLACK);
using (MemoryStream stream = new MemoryStream())
{
PdfReader reader = new PdfReader(bytes);
using (PdfStamper stamper = new PdfStamper(reader, stream))
{
int pages = reader.NumberOfPages;
for (int i = 1; i <= pages; i++)
{
ColumnText.ShowTextAligned(stamper.GetOverContent(i), Element.ALIGN_RIGHT, new Phrase(i.ToString(), blackFont), 568f, 15f, 0);
}
}
bytes = stream.ToArray();
}
File.WriteAllBytes(#"L:\Users\user\Documents\PDFnummerieren\PDF1.pdf", bytes);
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void button2_Click(object sender, EventArgs e)
{
this.Close();
}
private void button3_Click(object sender, EventArgs e)
{
var FD = new System.Windows.Forms.OpenFileDialog();
if (FD.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
fileToOpen = FD.FileName;
System.IO.FileInfo File = new System.IO.FileInfo(FD.FileName);
System.IO.StreamReader reader = new System.IO.StreamReader(fileToOpen);
}
}
}
}
I have put your variable to class scope and now you can access it from anywhere inside your class
Here is a question very close to mine (I think): Running a method in BackGroundWorker and Showing ProgressBar
Here is my code, it's not freezing my Main form anymore but the function doesn't do its job.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using YoutubeSearch;
namespace searchyoutubeTest
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
myBGWorker.WorkerReportsProgress = true;
}
void myBGWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
myProgressBar.Value = e.ProgressPercentage;
}
void myBGWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
btnSearch.Enabled = true;
MessageBox.Show("Done");
}
private void myBGWorker_DoWork(object sender, DoWorkEventArgs e)
{
VideoSearch items = new VideoSearch();
List<Video> list = new List<Video>();
foreach (var item in items.SearchQuery(txtSearch.Text, 1))
{
Video video = new Video();
video.Title = item.Title;
video.Author = item.Author;
video.Url = item.Url;
byte[] imageBytes = new WebClient().DownloadData(item.Thumbnail);
using (MemoryStream ms = new MemoryStream(imageBytes))
{
video.Thumbnail = Image.FromStream(ms);
}
list.Add(video);
}
e.Result = list;
}
private void btnSearch_Click(object sender, EventArgs e)
{
btnSearch.Enabled = false;
myBGWorker.RunWorkerAsync();
//VideoSearch items = new VideoSearch();
//List<Video> list = new List<Video>();
//foreach (var item in items.SearchQuery(txtSearch.Text, 1))
//{
// Video video = new Video();
// video.Title = item.Title;
// video.Author = item.Author;
// video.Url = item.Url;
// byte[] imageBytes = new WebClient().DownloadData(item.Thumbnail);
// using (MemoryStream ms = new MemoryStream(imageBytes))
// {
// video.Thumbnail = Image.FromStream(ms);
// }
// list.Add(video);
//}
//videoBindingSource.DataSource = list;
}
private void txtSearch_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
btnSearch_Click(this, new EventArgs());
}
}
}
}
But if I do only the function, it works:
//VideoSearch items = new VideoSearch();
//List<Video> list = new List<Video>();
//foreach (var item in items.SearchQuery(txtSearch.Text, 1))
//{
// Video video = new Video();
// video.Title = item.Title;
// video.Author = item.Author;
// video.Url = item.Url;
// byte[] imageBytes = new WebClient().DownloadData(item.Thumbnail);
// using (MemoryStream ms = new MemoryStream(imageBytes))
// {
// video.Thumbnail = Image.FromStream(ms);
// }
// list.Add(video);
//}
//videoBindingSource.DataSource = list;
Any idea what I am doing wrong?
I assume you correctly added the events for the button and onload of the form.
You didnt attach the events for the BackgroundWorker. When you click on the searchbutton, the workers starts and the DoWork method is invoked on a seperate thread.
public Form1()
{
InitializeComponent();
myBGWorker.WorkerReportsProgress = true;
myBGWorker.DoWork += myBGWorker_DoWork;
myBGWorker.ProgressChanged += myBGWorker_ProgressChanged;
myBGWorker.RunWorkerCompleted += myBGWorker_RunWorkerCompleted;
}
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.Net;
using System.IO;
using HtmlAgilityPack;
using mshtml;
namespace Extract_Images
{
public partial class Form1 : Form
{
private string[] linkstoextract;
private int numberoflinks;
private int currentLinkNumber = 1;
private string mainlink;
private WebClient client;
private WebBrowser webBrowser1;
public Form1()
{
InitializeComponent();
webBrowser1 = new WebBrowser();
webBrowser1.ScriptErrorsSuppressed = true;
webBrowser1.DocumentCompleted += webBrowser1_DocumentCompleted;
label1.Text = "Number of links: ";
mainlink = "http://www.test.com";
numberoflinks = 211;
ProcessNextLink();
}
private void ProcessNextLink()
{
if (currentLinkNumber < numberoflinks)
{
currentLinkNumber++;
string linktonav = mainlink + "index"+currentLinkNumber.ToString() + ".html";
webBrowser1.Navigate(linktonav);
}
}
void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
ProcessImagesFromDocument();
ProcessNextLink();
}
private void ProcessImagesFromDocument()
{
IHTMLDocument2 doc = (IHTMLDocument2)webBrowser1.Document.DomDocument;
IHTMLControlRange imgRange = (IHTMLControlRange)((HTMLBody)doc.body).createControlRange();
foreach (IHTMLImgElement img in doc.images)
{
imgRange.add((IHTMLControlElement)img);
imgRange.execCommand("Copy", false, null);
using (Bitmap bmp = (Bitmap)Clipboard.GetDataObject().GetData(DataFormats.Bitmap))
{
if (bmp != null)
{
bmp.Save(#"d:\files\savedlinks\" + img.nameProp);
pictureBox1.Image = bmp;
}
}
}
}
private void Form1_Load(object sender, EventArgs e)
{
}
}
}
In the part:
using (Bitmap bmp = (Bitmap)Clipboard.GetDataObject().GetData(DataFormats.Bitmap))
{
if (bmp != null)
{
bmp.Save(#"d:\files\savedlinks\" + img.nameProp);
pictureBox1.Image = bmp;
}
}
Even if the bmp is not null after one iteration i'm getting exception on the bmp.Save line: Illegal characters in path
And i see in nameProp 395937.thumb?d=1348638415
The other problem is if i'm not using the lines:
bmp.Save(#"d:\files\savedlinks\" + img.nameProp);
pictureBox1.Image = bmp;
If i delete this two lines and using break point on the line:
if (bmp != null)
It will keep stop on this line for ever it will never stop it will keep stop on this line over and over again it will not stop on the foreach but only on this line.
What i want to do is to download from each link the images and also to make it optional to download specific images types like only jpg or only png.
Illegal characters in path error is because your file name is not a valid file name to save because it has invalid character like: '?'
Why the loop is endless, this need more debugging, Debug your code step by step, check the number of images on the first loop,
is it a huge unexpected number of images?
does the number increase on each loop? -> this may be a referencing issue.
"I have been trying to detect canny edge on an image and it has been successful, but I don't know how to detect its edge if I want it real time, here is my code, it has no error but the canny window can't be processed
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 KomCit;
using System.Drawing.Imaging;
using System.IO;
using System.Timers;
using AForge;
using AForge.Imaging.Filters;
using AForge.Video.DirectShow;
using System.Threading;
namespace canny_video
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private FilterInfoCollection CaptureDevice;
private VideoCaptureDevice FinalFrame;
void FinalFrame_NewFrame(object sender, AForge.Video.NewFrameEventArgs eventArgs)
{
CameraBox.Image = (Bitmap)eventArgs.Frame.Clone();
}
private static Image resizeImage(Image imgToResize, Size size)
{
return (Image)(new Bitmap(imgToResize, size));
}
private void Form1_Load(object sender, EventArgs e)
{
//timer1.Enabled = true;
CaptureDevice = new FilterInfoCollection(FilterCategory.VideoInputDevice);
foreach (FilterInfo Device in CaptureDevice)
{
listDevice.Items.Add(Device.Name);
}
listDevice.SelectedIndex = 0;
FinalFrame = new VideoCaptureDevice();
}
private void start_Click(object sender, EventArgs e)
{
FinalFrame = new VideoCaptureDevice(CaptureDevice[listDevice.SelectedIndex].MonikerString);
FinalFrame.NewFrame += new AForge.Video.NewFrameEventHandler(FinalFrame_NewFrame);
FinalFrame.Start();
//CannyBox.Image = (Bitmap)CameraBox.Image.Clone(); //capture image bitmap
//Bitmap gambar = new Bitmap(CameraBox.Image);
Bitmap gambar = new Bitmap(CameraBox.Image);
Grayscale gray = new Grayscale(0.2125, 0.7154, 0.0721);
CannyEdgeDetector cany = new CannyEdgeDetector(0, 70);
Bitmap hasil = cany.Apply(gray.Apply(gambar));
// BlobsFiltering blob = new BlobsFiltering(0, 0, 20, 20);
//Bitmap hasil = blob.Apply(gray.Apply(gambar));
//CannyBox.Width = gambar.Width;
//CannyBox.Height = gambar.Height;
CannyBox.Image = hasil;
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
if (FinalFrame.IsRunning == true)
{
FinalFrame.Stop();
}
}
}
}
"
My problem above is solved, thank you :)
but I have another problem on integral projection, I didn't know how to do it though.
please help, thank you in advance
Some comments:
Your two private variables are very confusingly named. Your CaptureDevice is a collection of all the capture devices on the computer, while your FinalFrame is a capture device.
You do not look for canny edges on the bitmap upon reception.
The NewFrame event handler runs in the streaming thread, so you should use a .BeginInvoke in there to make it usable by the UI thread.
What you may do:
Inside _NewFrame handler, use BeginInvoke to transfer the cloned image to a ProcessCameraImage method (that will hence run on the UI thread).
Apply canny edge detection within this method.
Then assign the result to your picture box.
Note: I don't know how CPU heavy canny edge detection is. If it's costly, doing it on the UI thread may block user interaction. In that case you could do it within the streaming thread and only transfer the processed image for display. But depending on the time it takes, this may force the camera to lower its framerate.
thank you for your answer, it has been solved just now, I've modified it and it somehow solved
here 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 AForge;
using AForge.Imaging;
using AForge.Imaging.Filters;
using AForge.Video;
using AForge.Video.DirectShow;
using System.Drawing.Imaging; //Save P2
using System.IO; //Save P2
namespace AForgeCamera
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
Bitmap video;
private FilterInfoCollection CaptureDevice;
private VideoCaptureDevice FinalFrame;
int mode;
private void Form1_Load(object sender, EventArgs e)
{
CaptureDevice = new FilterInfoCollection(FilterCategory.VideoInputDevice);
foreach (FilterInfo Device in CaptureDevice)
{
comboBox1.Items.Add(Device.Name);
}
comboBox1.SelectedIndex = 0;
FinalFrame = new VideoCaptureDevice();
}
private void button1_Click(object sender, EventArgs e) //Tombol Start
{
FinalFrame = new VideoCaptureDevice(CaptureDevice[comboBox1.SelectedIndex].MonikerString);
FinalFrame.NewFrame += new NewFrameEventHandler(FinalFrame_NewFrame);
FinalFrame.Start();
}
void FinalFrame_NewFrame(object sender, NewFrameEventArgs eventArgs)
{
video = (Bitmap)eventArgs.Frame.Clone();
Bitmap video2 = (Bitmap)eventArgs.Frame.Clone();
if (mode==1)
{
Grayscale gray = new Grayscale(0.2125, 0.7154, 0.0721);
Bitmap video3 = gray.Apply(video2);
CannyEdgeDetector canny = new CannyEdgeDetector(0, 70);
canny.ApplyInPlace(video3);
pictureBox2.Image = video3;
}
pictureBox1.Image = video;
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
if (FinalFrame.IsRunning == true)
{
FinalFrame.Stop();
}
}
private void btnTrackingObject_Click(object sender, EventArgs e)
{
mode = 1;
}
}
}
but now I am working on the next problem, I try to detect the location of the object using integral projection, is it possible to use aforge to do it?
I'm having some trouble, somehow I get a "not allowed exception" and I can't seem to figure out what is wrong I know the answer is simple but I really can't spot what's wrong with my code...
it happens when I try to write something to the newly created file and I could imagine that it also will when it tries to read the file... any information would be acknowledged...
thx in advance
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text; // ny
using System.Net;
using System.Collections.Specialized;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Tasks;
using Microsoft.Phone.Shell;
using System.IO; // ny
using System.IO.IsolatedStorage; // ny
namespace SmartSence
{
public partial class MainPage : PhoneApplicationPage
{
private static UTF8Encoding enc = new UTF8Encoding();
// Constructor
public MainPage()
{
InitializeComponent();
if (CreateStore().FileExists("Userdata\\Userdata.txt"))
{
mail.Text = ReadFile(CreateStore());
}
}
private void minknap_Click(object sender, RoutedEventArgs e)
{
string newusername;
newusername = Username.Text;
mytext1.Text = newusername;
string igen;
igen = "&password=";
string newpassword;
newpassword = mypassword.Password;
mypasswordblock.Text = newpassword;
WebBrowserTask webBrowserTask = new WebBrowserTask();
webBrowserTask.Uri = new Uri("http://www.smartsence.dk/winindexcheck.php?id=" + mytext1.Text + igen + mypasswordblock.Text, UriKind.Absolute);
webBrowserTask.Show();
}
private void signin_Click(object sender, RoutedEventArgs e)
{
string signin;
signin = mail.Text;
signintext.Text = signin;
string igen;
igen = "&password=";
string newpassword;
newpassword = mail.Text;
signintext.Text = newpassword;
if (!CreateStore().DirectoryExists("Userdata"))
{
CreateStore().CreateDirectory("Userdata");
if (!CreateStore().FileExists("Userdata\\data.txt"))
{
CreateStore().CreateFile("Userdata\\data.txt");
}
IsolatedStorageFileStream stream = new IsolatedStorageFileStream("Userdata\\Userdata.txt", FileMode.Create, CreateStore());
WriteToFile(CreateStore(), signin);
}
WebBrowserTask webBrowserTask = new WebBrowserTask();
webBrowserTask.Uri = new Uri("http://www.smartsence.dk/winindexcheck.php?id=" + signintext.Text + igen + signintext.Text, UriKind.Absolute);
webBrowserTask.Show();
}
private void minknap2_Click(object sender, RoutedEventArgs e)
{
NavigationService.Navigate(new Uri("/Info.xaml", UriKind.Relative));
}
private void PhoneApplicationPage_Loaded(object sender, RoutedEventArgs e)
{
}
private void info_Click(object sender, EventArgs e)
{
MessageBox.Show("SmartSence App 4.0 - Is free to use, it´s has never been easier to navigate around the web. Buy the app and get free VIP status forever - Please support us :) ");
}
private void VIP_Click(object sender, EventArgs e)
{
WebBrowserTask webBrowserTask = new WebBrowserTask();
webBrowserTask.Uri = new Uri("http://www.smartsence.dk/winindexappvipcheck2.php", UriKind.Absolute);
webBrowserTask.Show();
}
private void image1_ImageFailed(object sender, ExceptionRoutedEventArgs e)
{
}
#region NewMethods
private IsolatedStorageFile CreateStore()
{
IsolatedStorageFile lager = IsolatedStorageFile.GetUserStoreForApplication();
return lager;
}
private void WriteToFile(IsolatedStorageFile storeFile, string content)
{
IsolatedStorageFileStream fileStream = storeFile.OpenFile("Userdata\\Userdata.txt", FileMode.Open, FileAccess.Write); // Exception: not allowed on IsolatedStorageFile
using (StreamWriter writer = new StreamWriter(fileStream))
{
writer.WriteLine(content);
}
}
private string ReadFile(IsolatedStorageFile storeFile)
{
IsolatedStorageFileStream fileStream = storeFile.OpenFile("Userdata\\Userdata.txt", FileMode.Open, FileAccess.Read);
using (StreamReader reader = new StreamReader(fileStream))
{
return reader.ReadLine().Trim();
}
}
private void mail_Tap(object sender, GestureEventArgs e)
{
mail.Text = string.Empty;
}
#endregion
}
}
I think the issue is that you're not closing your IsolatedStorageFileStream, so the file is still open, and hence cannot be written, therefore throwing this exception. You should make sure to wrap your reads & writes in a using, or calling Dispose yourself.
public MainPage()
{
InitializeComponent();
if (CreateStore().FileExists("Userdata\\Userdata.txt"))
{
mail.Text = ReadFile(CreateStore()); //opens file and never closes it.
}
}
To fix this, you should use using statements.
private void WriteToFile(IsolatedStorageFile storeFile, string content)
{
using (IsolatedStorageFileStream fileStream = storeFile.OpenFile("Userdata\\Userdata.txt", FileMode.Open, FileAccess.Write){ // Exception: not allowed on IsolatedStorageFile
using (StreamWriter writer = new StreamWriter(fileStream))
{
writer.WriteLine(content);
}
}
}
private string ReadFile(IsolatedStorageFile storeFile)
{
using(IsolatedStorageFileStream fileStream = storeFile.OpenFile("Userdata\\Userdata.txt", FileMode.Open, FileAccess.Read){
using (StreamReader reader = new StreamReader(fileStream))
{
return reader.ReadLine().Trim();
}
}
}