HI I have several xml files , I select them using open file dialog, then delete duplicate data from those files and now I wanted every individual files to saved as.bak file I can select multiple files and delete those data from files but dont no how to save those files after deleting.
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.Xml;
using System.Xml.Linq;
using System.IO.Path;
namespace XML_Deletes
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button2_Click(object sender, EventArgs e)
{
//single indivual file
var doc = XDocument.Load(#"C:\\Users\IT-Administrator\Desktop\21.xml");
doc.Root.Elements("Incident")
.GroupBy(s => (string)s.Element("Comment"))
.SelectMany(g => g.Skip(1))
.Remove();
//doc.Save(#"C:\Users\IT-Administrator\Desktop\22.xml");
}
private void button1_Click(object sender, EventArgs e)
{
OpenFileDialog openFileDialog1 = new OpenFileDialog();
openFileDialog1.Filter = "XML files(.xml)|*.xml|all Files(*.*)|*.*";
openFileDialog1.FilterIndex = 1;
openFileDialog1.Multiselect = true;
if(openFileDialog1.ShowDialog() == DialogResult.OK)
{
{
if (!String.Equals(Path.GetExtension(openFileDialog1.FileName),
".xml",
StringComparison.OrdinalIgnoreCase))
{
// Invalid file type selected; display an error.
MessageBox.Show("The type of the selected file is not supported by this application. You must select an XML file.",
"Invalid File Type",
MessageBoxButtons.OK,
MessageBoxIcon.Error);
}
else
{
}
} }
}
}
Are you looking for XDocument.Save?
doc.Save(#"C:\\Users\IT-Administrator\Desktop\21.xml");
That's already in your code (though its commented out?). Are you having issues saving?
Related
I am using EmguCV in Visual Studio 2022 and I am simple trying to read and open my image but it only opens .tif image files not .jpg or any other file...
When I try to open any .jpg file it gives me an exception openCV:index out of bound
Here:
I also debugged it and find something like it is not reading file when I passed it to EmguCV image structure "Image<Bgr,byte> imgFile=new Image<Bgr,byte>(filename)"
while it is loading file from dialogue but not passing forward from this structure.
Here's the Debug SS:
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 Emgu;
using Emgu.CV;
using Emgu.CV.Structure;
using Emgu.CV.Util;
namespace test_EmguCV
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void openToolStripMenuItem_Click(object sender, EventArgs e)
{
try
{
OpenFileDialog ofd = new OpenFileDialog();
if (ofd.ShowDialog() == DialogResult.OK)
{
Image<Bgr, byte> imgFile = new Image<Bgr, byte>(ofd.FileName);
pictureBox1.Image = imgFile.Bitmap;
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void exToolStripMenuItem_Click(object sender, EventArgs e)
{
this.Close();
}
}
}
Another Imp:
My friend is also doing the same work with me and he is using the same ide same mehtods same references same dll files but his is running fine but not of mine..
I just tried your code snippet in a new Form and I can say that I can successfully load a .jpg image and display it in a PictureBox. Make sure your image is not corrupted in the first place.
Here's my code:
private void button1_Click(object sender, EventArgs e)
{
try
{
OpenFileDialog ofd = new OpenFileDialog();
if (ofd.ShowDialog() == DialogResult.OK)
{
Image<Bgr, byte> imgFile = new Image<Bgr, byte>(ofd.FileName);
pictureBox1.Image = imgFile.ToBitmap();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
Note that it's imgFile.ToBitmap(), not imgFile.Bitmap()
Also I would suggest you to switch to Mat instead of Image<>. More info from OpenCV docs
With Mat the code to get the image is as easy as:
Mat imgFile = new Mat(ofd.FileName);
More info about Mat in EmguCV here
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 Microsoft.VisualBasic.FileIO;
using System.Management;
namespace test_code
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
FolderBrowserDialog folderDlg = new FolderBrowserDialog();
//folderDlg.ShowDialog();
if (folderDlg.ShowDialog() != DialogResult.OK)
{
return;
}
// Has different framework dependend implementations
// in order to handle unauthorized access to subfolders
RenamePngFiles(folderDlg.SelectedPath);
}
private void RenamePngFiles(string directoryPath)
{
int fileNameSuffixCounter = 1;
foreach (string originalFullFileName in System.IO.Directory.EnumerateFiles(directoryPath, "*.png", new EnumerationOptions()))
{
// The new file name without path
var newFileName = $"{System.IO.Path.GetFileNameWithoutExtension(originalFullFileName)}#{fileNameSuffixCounter++}{System.IO.Path.GetExtension(originalFullFileName)}";
FileSystem.RenameFile(originalFullFileName, newFileName);
}
}
}
}
Above is my code and I am not sure why i am not able to remove the above error. I tried all sorts of namespace and i cannot of get rid of it. I am using .netframework 4.7.2.
AS you can see all I am trying to do is rename all the files in a folder including subfolder to append with # and a number which keep on increasing depending on the number of files in a folder.
Combined with the comments above, I made the following changes.
Updated:
Modify all png files in the selectedPath.
RenameAllPngFiles(folderDlg.SelectedPath);
The following are custom functions:
Rename all png files :
private void RenameAllPngFiles(string directoryPath) {
RenameCurrentPng(directoryPath);
foreach (var item in GetDirectoryInfos(directoryPath)) {
RenameCurrentPng(item.FullName);
}
}
Rename all png files in the current directory:
private void RenameCurrentPng(string directoryPath) {
int fileNameSuffixCounter = 1;
foreach (string originalFullFileName in Directory.EnumerateFiles(directoryPath, "*.png")) {
// The new file name without path
var newFileName = $"{System.IO.Path.GetFileNameWithoutExtension(originalFullFileName)}#{fileNameSuffixCounter++}{System.IO.Path.GetExtension(originalFullFileName)}";
FileSystem.RenameFile(originalFullFileName, newFileName);
}
}
Get the addresses of all subfolders :
private DirectoryInfo[] GetDirectoryInfos(string directoryPath) {
DirectoryInfo di = new DirectoryInfo(directoryPath);
DirectoryInfo[] directories = di.GetDirectories("*", System.IO.SearchOption.AllDirectories);
return directories;
}
If you have questions about my code, please comment below and I will follow up.
Hello I was writing a basic text editor in C# on visual studio windows form using the .NET framework 3.1 long term support version everything worked fine until I wrote the save file script
Here's the code for "Form1.cs" which is where the open and save file functions reside
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;
using System.Security.Principal;
namespace Text_Editor
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
string locsave;
private void openbtn_Click(object sender, EventArgs e)
{
var identity = WindowsIdentity.GetCurrent();
var principal = new WindowsPrincipal(identity);
if (principal.IsInRole(WindowsBuiltInRole.Administrator) != true)
{
MessageBox.Show("Run as Admin");
System.Windows.Forms.Application.ExitThread();
}
else
{
OpenFileDialog openfile = new OpenFileDialog();
if (openfile.ShowDialog() == DialogResult.OK)
{
var locationArray = openfile.FileName;
string location = "";
locsave = locationArray;
foreach (char peice in locationArray)
{
location = location + peice;
}
var contentArray = File.ReadAllText(location);
string content = "";
label4.Text = location;
foreach (char peice in contentArray)
{
content = content + peice;
}
richTextBox1.Text = content;
}
}
}
private void Form1_Load(object sender, EventArgs e)
{
Console.WriteLine("Test");
}
private void savebtn_Click(object sender, EventArgs e)
{
if (#label4.Text == "")
{
MessageBox.Show("Open a text file first");
}
else
{
StreamWriter outputfile = new StreamWriter(locsave);
outputfile.Write(richTextBox1.Text); //this is where the error occures and it throws the error of access denyed
outputfile.Close();
}
}
}
}
Does anyone have a suggestion about what to do I looked around on google for a solution but it seemed most did not work and some others I did not understand.
I'm trying to make a code that converts memorystream to a png image, but I'm getting a ArgumentException "parameter is incorrect" error on using(Image img = Image.FromStream(ms)). It doesn't specify it any further so I don't know why I'm getting the error and what am I supposed to do to it.
Also, how do I use the Width parameter with img.Save(filename + ".png", ImageFormat.Png);? I know I can add parameters and it recognizes "Width", but I have no idea how it should be formatted so visual studio would accept it.
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;
using System.Drawing.Imaging;
namespace WindowsFormsApp1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
MemoryStream ms = new MemoryStream();
public string filename;
private void button1_Click(object sender, EventArgs e)
{
OpenFile();
}
private void button2_Click(object sender, EventArgs e)
{
ConvertFile();
}
private void OpenFile()
{
OpenFileDialog d = new OpenFileDialog();
if(d.ShowDialog() == DialogResult.OK)
{
filename = d.FileName;
var fs = d.OpenFile();
fs.CopyTo(ms);
}
}
private void ConvertFile()
{
using(Image img = Image.FromStream(ms))
{
img.Save(filename + ".png", ImageFormat.Png);
}
}
}
}
I suspect the problem is with how you're reading the file here:
fs.CopyTo(ms);
You're copying the content of the file into the MemoryStream, but then leaving the MemoryStream positioned at the end of the data rather than the start. You can fix that by adding:
// "Rewind" the memory stream after copying data into it, so it's ready to read.
ms.Position = 0;
You should consider what happens if you click on the buttons multiple times though... and I'd strongly advise you to use a using directive for your FileStream, as currently you're leaving it open.
I am using ExcelDataReader here.
I don't know why below code doesn't work.
It doesn't generate any error but it still doesn't show excel data.
It simply doesn't do anything after loading excel file.
I am new to C# and after 5 hours of digging I feel frustrated since I don't know why this doesn't work.
using Excel;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WindowsFormsApplication5
{
public partial class ExcelForm : Form
{
public ExcelForm()
{
InitializeComponent();
}
private void ExcelForm_Load(object sender, EventArgs e)
{
}
DataSet result;
private void btnOpen_Click(object sender, EventArgs e)
{
using (OpenFileDialog ofd = new OpenFileDialog() { Filter = "Excel(.xls)|*.xls|Excel(.xlsx)|*.xlsx", ValidateNames = true })
{
if(ofd.ShowDialog() == DialogResult.OK)
{
FileStream fs = File.Open(ofd.FileName, FileMode.Open, FileAccess.Read);
IExcelDataReader reader;
if (ofd.FilterIndex == 1)
reader = ExcelReaderFactory.CreateBinaryReader(fs);
else
reader = ExcelReaderFactory.CreateOpenXmlReader(fs);
reader.IsFirstRowAsColumnNames = true;
result = reader.AsDataSet();
reader.Close();
dataGridView.DataSource = result;
}
}
}
}
}
dataGridView.DataSource = DtSet.Tables[0];