I have been working on converting a GUI script from another language to C# using VS2017. I have the whole thing working for the most part, but have come on a problem. The gui has a listview which I am populating either manually through entering data in various fields or as an import from a CSV. The manual entry works just fine. The CSV import works as well, however it is pulling the header line into the listview. Here is the code I am using for the button to kick off the import:
private void import(object sender, RoutedEventArgs e)
{
OpenFileDialog xls = new OpenFileDialog();
xls.Multiselect = false;
xls.Filter = "CSV files (*.csv)|*.csv";
xls.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory);
xls.ShowDialog();
string ins;
if (xls.FileName != null)
{
FileStream srcFS;
srcFS = new FileStream(xls.FileName, FileMode.Open);
StreamReader srcSR = new StreamReader(srcFS, System.Text.Encoding.Default);
do
{
ins = srcSR.ReadLine();
if (ins != null)
{
string[] parts = ins.Split(',');
MyItems.Add(new MyItem
{
Name = parts[0],
CPU = parts[1],
RAM = parts[2],
IP = parts[3],
Subnet = parts[4],
PortGroup = parts[5],
Gateway = parts[6],
DNS = parts[7],
Description = parts[8],
Template = parts[9],
Host = parts[10],
Site = parts[11],
Folder = parts[12],
Datastore = parts[13],
Patch = parts[14],
HDD1_Size = parts[15],
HDD2_Size = parts[16],
HDD3_Size = parts[17],
HDD4_Size = parts[18],
HDD5_Size = parts[19],
HDD6_Size = parts[20],
HDD7_Size = parts[21],
HDD8_Size = parts[22],
HDD9_Size = parts[23],
HDD10_Size = parts[24]
});
}
} while (ins != null);
srcSR.Close();
}
}
I have been googling for some ways to skip the first line, but it most of the suggestions have been to iterate through line by line and write the lines one at a time, which slows the import process (there could be hundreds of lines). Just curious if there is a simple way to tell the StreamReader where to begin reading the file.
You want to read a line and throw it away. Just add an ins = srcSR.ReadLine(); right above your do.
Related
my application is in C# MVC with framework 4.5.2 and want to run external file(.m) and get output from that and it is written in Octave.
Note: Output result is in a string, so I have to show that output in C# html page.
Algorithm is written in octave and also in algorithm excel file is there to read data and external parameters are also passing through C#.
I tried the things which is already posted, the main concern is that my application is hosted in azure cloud. So, I can not install octave in cloud.
Can you suggest me any other way that directly run external file(.m) with dynamic excel file and parameters.
I can show my code what I have done. Its work in local with all but I can not install Octave in Azure cloud..
I put my installed folder to root path on server but its also not working.
public Octave(string pathToOctaveBinaries, bool createWindow)
{
StartOctave(pathToOctaveBinaries, createWindow);
}
private void StartOctave(string pathToOctaveBinaries, bool createWindow)
{
_ptob = pathToOctaveBinaries;
cw = createWindow;
this.OctaveEchoString = Guid.NewGuid().ToString();
OctaveProcess = new Process();
ProcessStartInfo pi = new ProcessStartInfo();
if (pathToOctaveBinaries[pathToOctaveBinaries.Length - 1] != '\\')
pathToOctaveBinaries = pathToOctaveBinaries + "\\";
pi.FileName = pathToOctaveBinaries + "octave-cli.exe";
pi.RedirectStandardInput = true;
pi.RedirectStandardOutput = true;
pi.RedirectStandardError = true;
pi.UseShellExecute = false;
pi.CreateNoWindow = !createWindow;
pi.Verb = "open";
//
pi.WorkingDirectory = ".";
OctaveProcess.StartInfo = pi;
OctaveProcess.Start();
OctaveProcess.OutputDataReceived += new DataReceivedEventHandler(OctaveProcess_OutputDataReceived);
OctaveProcess.BeginOutputReadLine();
OctaveEntryText = ExecuteCommand(null);
}
public string ExecuteCommand(string command, int timeout)
{
if (OctaveProcess.HasExited)
{
StartOctave(_ptob, cw);
if (OctaveRestarted != null) OctaveRestarted(this, EventArgs.Empty);
}
_exitError = false;
Thread tmp = new Thread(new ParameterizedThreadStart(WorkThread));
tmp.Start(command);
if (!tmp.Join(timeout))
{
tmp.Abort();
throw new Exception("Octave timeout");
}
if (_exitError)
{
throw new Exception(_errorMessage);
}
return SharedBuilder.ToString();
}
This above is Octave class file. Where I dynamically pass the path of .exe to be run as thread.
Controller Code:
Octave octave = new Octave(OctaveFilePath, false);
string fileData = result.Data.ToString();
fileData = fileData.Replace("#ExcelFilePath#", excelFilePath);
fileData = fileData.Replace("#ABCD#", historyData);
string rasp = octave.ExecuteCommand(fileData, 30000);
From here I get string and that I show into html page.
This is my code.
public static string LoadPackage(DirectoryInfo outputDir, string name)
{
FileInfo newFile = new FileInfo(outputDir.FullName + #"\test.xlsx");
if (newFile.Exists)
{
newFile.Delete();
newFile = new FileInfo(outputDir.FullName + #"\test.xlsx");
}
var format = new ExcelTextFormat();
format.Delimiter = '\t';
format.SkipLinesBeginning = 1;
using (ExcelPackage package = new ExcelPackage())
{
LoadSheet(package, outputDir, name);
package.SaveAs(newFile);
}
return newFile.FullName;
}
And after that i call LoadSheet method in order to fill my excel file from tsv file.
public static void LoadSheet(ExcelPackage package, DirectoryInfo
outputDir, string name)
{
var ws = package.Workbook.Worksheets.Add("Content");
var format = new ExcelTextFormat();
format.Delimiter = '\t';
format.SkipLinesBeginning = 2;
format.SkipLinesEnd = 1;
var range = ws.Cells["A1"].LoadFromText(new
FileInfo(outputDir.FullName + "\\" + name), format,
TableStyles.Medium27, false);
}
And this is my code on button click event
if (BrowseFileUpload.HasFile)
{
var name = BrowseFileUpload.PostedFile.FileName;
InputTextBox.Text = name;
LoadData.LoadPackage(new
System.IO.DirectoryInfo("C:\\Users\\Nemanja\\Downloads"), name);
InfoLabel.Text = "Your data has been imported!!!";
InfoLabel.ForeColor = System.Drawing.Color.Blue;
InfoLabel.Font.Size = 20;
}
Everything is ok i create new excel file, sheet save it but it does not load data that i need it to load inside excel file. It's only empty file or i get a error the file is corrupted recover what you can.
Can someone figure out what can be a problem based on my explanation and this code. Thank you all good people.
I think that the problem may well be with the format of your source data. I've put together the following sample, based on your code, and it works fine.
var outFile = Path.ChangeExtension(filePath, ".xlsx");
using (var p = new ExcelPackage())
{
var fmt = new ExcelTextFormat();
fmt.Delimiter = '\t';
fmt.SkipLinesBeginning = 2;
fmt.SkipLinesEnd = 1;
fmt.EOL = ((char)10).ToString(); // THIS LINE FIXED THE PROBLEM (UNIX NEWLINE)
var ws = p.Workbook.Worksheets.Add("Imported Text");
ws.Cells[1, 1].LoadFromText(new FileInfo(filePath), fmt, TableStyles.Medium27, false);
p.SaveAs(new FileInfo(outFile));
}
Try running your data through this and see if you get the same issue or not.
UPDATED
The problem was a unix-style newline in the file - EPPlus expects a windows-style newline by default
I have to import data from a text file to a flat file database. I'm sure there's a faster way to load all the data into the database but I don't know how.
private void ImportButton_Click(object sender, EventArgs e)
{
string Path = string.Empty;
OpenFileDialog ofd = new OpenFileDialog();
ofd.Filter = "Text File|*.txt";
ofd.ShowDialog();
if (ofd.FileName == string.Empty) return
Path = ofd.FileName;
string data;
using (var sr = new StreamReader(Path))
{
data = sr.ReadToEnd();
}
var items = data.Split(new[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries);
var count = 0;
foreach (var info in items.Select(ItemInfo.FromText).Where(info => info != null))
{
count++;
info.Index = ++Envir.ItemIndex;
Envir.ItemInfoList.Add(info);
}
MessageBox.Show(count + " Items have been imported");
UpdateInterface(true);
}
If you're doing this via C#, then I'd recommend SqlBulkCopy. I provided a similar answer to another question a while back. See that link for an example of how I've implemented it in the past.
If you want to know other options available to you then MSDN has quite a good list of options in their data loading guide; http://msdn.microsoft.com/en-us/library/dd425070(v=sql.100).aspx
I want the user to be able to chose a text file written in a certain way (1 number per line) and then have the file converted into an array. I have bits and pieces of it working but I cant get it to all work at the same time. Any help would be appreciated.
private void Load_Button_Click(object sender, EventArgs e)
{
int counter = 0;
string line;
List<int> list = new List<int>();
string fileName = "";
//OpenFileDialog ofd = new OpenFileDialog();
//ofd.Filter = "TXT File|*.txt";
//ofd.Title = "Open File";
// if (ofd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
// {
File_Label.Text = "C:/Users/Neilan/Desktop/sample.txt";
//fileName = "#" + ofd.SafeFileName;
//MessageBox.Show(ofd.FileName);
System.IO.StreamReader file = new System.IO.StreamReader(#"C:\Users\Neilan\Desktop\sample.txt");
while ((line = file.ReadLine()) != null)
{
Unsorted_Box.Text += line + ", ";
//list.Add(int.Parse(fileName));
counter++;
}
dataArray = list.ToArray();
// }
}
You can do this.
var numberarray = File.ReadAllLines("stringpath").Select(int.Parse).ToArray();
Looking at your code, I guess you want to show these values in comma separated format to user. You can achieve this with following code snippet.
Unsorted_Box.Text = String.Join(",", numberarray.ToArray());
Hope this helps !
This problem can be solved by one line
var resultArray = Array.ConvertAll(System.IO.File.ReadAllLines("filename.type"), str => int.Parse(str));
Instead of "filename.type" you can put something like File_Label.Text
In the code below, the console prompts the user for 2 files (currently in a networked location). It then copies those files to the local drive for quicker reading of the PDF, but I'm running into a problem. If I reference the last line of code as PdfDocument pdf = new PdfDocument("C:\somepdf.pdf"); the file is accessed extremely quickly.
However, with the current copy processes, for some reason, this line of code alone is taking upwards of 18-20 minutes to process. I'm assuming that this is because the file, having recently been copied, is still locked under a process, even though the actual copy process takes less than 10 seconds.
In my research, I have seen various ways of identifying the process that's locking the file and killing it, but this doesn't seem to apply to what I'm trying to do.
Unfortunately, I'm to the point where I have to ask for help. Am I overlooking something here? I don't see why it would take 15 less minutes to process a pdf referenced locally, than one processed by a copy process, then locally.
Thoughts?
string selectFileNameO;
string selectFileNameF;
string FileNameO;
string FileNameF;
using (OpenFileDialog dialog = new OpenFileDialog())
{
dialog.Title = "Choose File";
dialog.FileName = "";
dialog.ShowDialog();
selectFileNameO = dialog.FileName;
}
string ext = System.IO.Path.GetExtension(selectFileNameO);
selectFileNameF = Path.GetFileName(selectFileNameO);
selectFileNameF = selectFileNameF.Substring(0, selectFileNameF.Length - ext.Length);
selectFileNameF = "C:\\" + selectFileNameF + ".ext";
Console.WriteLine(selectFileNameF);
using (OpenFileDialog dialog2 = new OpenFileDialog())
{
dialog2.Title = "Choose 2 File";
dialog2.FileName = "";
dialog2.ShowDialog();
FileNameO = dialog2.FileName;
}
string ext1 = System.IO.Path.GetExtension(FileNameO);
FileNameF = Path.GetFileName(FileNameO);
FileNameF = FileNameF.Substring(0, FileNameF.Length - ext1.Length);
FileNameF = "C:\\" + FileNameF + ".ext";
File.Copy(FileNameO, FileNameF, true);
int distanceToString = 535;
int lengthOfString = 6;
string myDataSet;
using (StreamReader sr = new StreamReader(selectFileNameF))
{
while (!sr.EndOfStream)
{
string line = sr.ReadLine();
myDataSet = line.Substring(distanceToString, lengthOfString);
selectFileUIDs.Add(myDataSet);
Console.WriteLine(myDataSet);
}
sr.Dispose();
}
Console.WriteLine(FileNameF);
PdfDocument pdf = new PdfDocument(FileNameF);