BenchmarkDotNet не показывает скорость работы с StreamReader - c#

I want to learn how to measure the running time of pieces of code, but judging by the information on the Internet, there are a lot of subtleties that need to be taken into account, so I'm trying to figure out BenchmarkDotNet (only the running time, the rest of the features do not care yet).
As you can see from the picture, the time is not shown (NA), although I did everything according to the templates. Actually, what's wrong?
It will be great if someone writes what exactly needs to be added/removed, and not just gives general recommendations. I'm learning the basics of C#, and haven't even gotten to OOP, so it's hard for me to understand you without your code.
Thank you Google for translating from Russian to English.
using System;
using System.Text;
using System.IO;
using System.Text.RegularExpressions;
using System.Collections.Generic;
using BenchmarkDotNet.Attributes;
using BenchmarkDotNet.Running;
namespace ConsoleApp2
{
public class Program
{
[Benchmark]
public void NotePad()
{
string path = #"..\..\..\first_million_prime_number\primes1.txt";
var sr = new StreamReader(path, Encoding.Default);
List<int> numbers = new List<int>();
string line;
while ((line = sr.ReadLine()) != null)
{
if (line.Length == 0) continue;
for (int i = 0; i < 80; i += 10)
numbers.Add(Convert.ToInt32(line.Substring(i, 10)));
}
sr.Close();
}
static void Main(string[] args)
{
BenchmarkRunner.Run<Program>();
}
}
}

Related

error return keyword must not be followed by an object expression

The return(match) is giving me a headache! When I change it into Console.WriteLine(match) it gives me the return I expect but when I try to use the return(match) it gives me an error. I just don't know what to change here so any suggestions would be appreciated!
regards, James
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
namespace ReadTextFile
{
class Program
{
static void Main(string[] args)
{
List<string> fileLines = new List<string>();
using (var reader = new StreamReader("test.txt"))
{
string line;
while ((line = reader.ReadLine()) != null)
{
fileLines.Add(line);
string pattern = #"(\w+)#(\w+).([a-z]+)";
Match match = Regex.Match((line), pattern);
if (match.Success)
{
return(match);
}
}
}
Main returns a void if you want to return something else change the signature. Note that typically the return value of Main is called an error code where non-zero is considered an error.
If you create another function and put your logic into it you could then use return.
On the other hand if all you are looking to do is leave the while you instead need to make Match match; be after string line; and use break; to get out instead of return.
You're in a void method (void Main). void methods do not have a return value, so just return; by itself is all that's allowed.
BTW, return is not a function in C#, it's a statement, so there is no need for parenthesis.

fetching only one url in c#

I am working on collecting urls from the web site in C# using WatiN framework. In my program it is fetching only one url. I don't know what is the problem. Any help will be appreciated.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using WatiN.Core;
using WatiN.Core.Native.InternetExplorer;
namespace magicbricks
{
class scroll
{
[STAThread]
static void Main(string[] args)
{
Browser browserInstance;
browserInstance = new IE(#"http://www.99acres.com/property-in-chennai- ffid?search_type=QS&search_location=CP32&lstAcn=CP_R&lstAcnId=32&src=CLUSTER&isvoicesearch=N&keyword_suggest=chennai%20%28all%29%3B&fullSelectedSuggestions=chennai%20%28all%29&strEntityMap=W3sidHlwZSI6ImNpdHkifSx7IjEiOlsiY2hlbm5haSAoYWxsKSIsIkNJVFlfMzIsIFBSRUZFUkVOQ0VfUywgUkVTQ09NX1IiXX1d&texttypedtillsuggestion=chennai&refine_results=Y&Refine_Localities=Refine%20Localities&action=%2Fdo%2Fquicksearch%2Fsearch&suggestion=CITY_32%2C%20PREFERENCE_S%2C%20RESCOM_R");
foreach (var links in browserInstance.Links.Filter(Find.ByClass("b")))
{
Console.WriteLine(links.Url);
String filePath = "C:/Users/User/Desktop/New folder";
String fileName = "newop4.csv";
using (StreamWriter sr = new StreamWriter(Path.Combine(filePath, fileName), true))
{
sr.WriteLine(links.Url);
}
Console.ReadLine();
}
}
}
}
the above code prints only one url in the console.
Remove the Console.ReadLine(); As you are in a ForEach loop. If you still want the Console.ReadLine(); move it out the foreach
The Console.ReadLine(); waits for a user input, after you enter any value you should see the next URL.

Issue trying to solve Project Euler #1

I'm having a problem trying to make a small app to solve Project Euler Problem #1.
Whenever I attempt to run this, it returns as 0, instead of 233168.
I'm not necessarily looking for an absolute answer, just some hints, I'm trying to learn.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
int x;
List<int> listOne = new List<int>();
for (x = 1; x < 1000; ++x)
{
if(x%3 == 0 || x%5 == 0)
{
listOne.Add(x);
}
Console.WriteLine(listOne.Sum());
Console.ReadLine();
}
}
}
}
In the interests of helping you learn, I'm not going to provide the exact answer.
Have a look at the scoping of your Console.WriteLine() statement. My guess is that it's not running when you think it should be.

Problems with MessageBox.Show()

I'm new to code and most things work, but I can't get this code to run. Can someone help?
I tried using System.Forms but it showed as missing a namespace. When I used using System.Windows.Forms that message went away. It does not let me use both.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Windows.Forms;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
StreamReader sr = new StreamReader(#"file.csv");
// for set encoding
// StreamReader sr = new StreamReader(#"file.csv", Encoding.GetEncoding(1250));
string strline = "";
String[] _values = null;
int x = 0;
while(!sr.EndOfStream)
{
strline = sr.ReadLine();
_values = strline.Split(',');
if (_values.Length >= 6 && _values[0].Trim().Length > 0)
{
MessageBox.show(_values[1]);
}
}
sr.Close();
}
}
}
There is no such namespace System.Forms, the class you were trying to use (MessageBox) is in System.Windows.Forms. By correcting your using statement, the error went away.
Remember, you must have a reference to System.Windows.Forms.dll in your console app to use this class.
You need to reference System.Windows.Forms.dll in your project. Here is a detailed instruction how to do that.
There is no such namespace as System.Forms there is only a namespace called System.Windows.Forms, wich has the MessageBox class you are talking about. To be able to use it, you need to add a reference to the System.Windows.Forms.dll to to your project (find it in the .NET Tab in the "Add Reference ..." dialog) and it will work. Also note that MessageBox.Show() requires a capital 'S'. Please see below an optimized and fully working version of your code.
using System.IO;
using System.Windows.Forms;
namespace ConsoleApplication7
{
class Program
{
static void Main(string[] args)
{
using (StreamReader sr = new StreamReader(#"file.csv"))
{
while (sr.Peek() >= 0)
{
string strline = sr.ReadLine();
string[] values = strline.Split(',');
if (values.Length >= 6 && values[0].Trim().Length > 0)
{
MessageBox.Show(values[1]);
}
}
}
}
}
}
You try use it in Console application first you should add System.Windows.Forms dll in your references (from .Net reference tab) then use it by adding it's namespace.
I'm a bit confused here. there is no namespace called System.Forms. It's always System.Windows.Forms. And the MessageBox class is defined in System.Windows.Forms
You need to manually ADD a reference to your project for System.Windows.Forms as you are on a console application and not a Windows Application. Just add the reference.

C# write multi lines to cs file

I googled and found the solution at MSDN.
// Compose a string that consists of three lines.
string lines = "First line.\r\nSecond line.\r\nThird line.";
// Write the string to a file.
System.IO.StreamWriter file = new System.IO.StreamWriter("c:\\test.txt");
file.WriteLine(lines);
file.Close();
How to extend the lines to complex content which including some natural C# code lines.
eg. I want to write the information below to my test.cs file.
Why?
I am parsing a XML schema with C# Console Application. And i want to generate the Console Result to a .cs file during the compiler time.
using System;
using System.Collections.Generic;
using System.Text;
namespace CommonDef
{
public class CCODEData
{
public int iCodeId;
public string sCode;
public CODEDType cType;
public int iOccures;
}
[Description("CodeType for XML schema.")]
public enum CODEDType
{
cString = 1,
cInt = 2,
cBoolean = 3,
}
thank you.
If your source code is hardcoded as in your sample, you could use a C# literal string:
string lines =
#"using System;
using System.Collections.Generic;
using System.Text;
namespace CommonDef
..."
Anyway in such cases it is a better idea (more readable and maintainable) to have the whole text contents into a text file as an embedded resource in your assembly, then read it using GetManifestResourceStream.
(I'm assuming you're trying to build up the result programmatically - if you genuinely have hard-coded data, you could use Konamiman's approach; I agree that using an embedded resource file would be better than a huge verbatim string literal.)
In your case I would suggest not trying to build up the whole file into a single string. Instead, use WriteLine repeatedly:
using (TextWriter writer = File.CreateText("foo.cs"))
{
foreach (string usingDirective in usingDirectives)
{
writer.WriteLine("using {0};", usingDirective);
}
writer.WriteLine();
writer.WriteLine("namespace {0}", targetNamespace);
// etc
}
You may wish to write a helper type to allow simple indentation etc.
If these suggestions don't help, please give more details of your situation.
I know an answer has already been accepted but why not use an XSLT applied to the XML instead? this would mean that you could easily generate c#, vb.net, .net without having to recompile the app.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace FileHandling
{
class Class1
{
static void Main()
{
Console.WriteLine("Enter data");
ConsoleKeyInfo k;
//Console.WriteLine(k.KeyChar + ", " + k.Key + ", " + k.Modifiers );
string str="";
char ch;
while (true)
{
k = Console.ReadKey();
if ((k.Modifiers == ConsoleModifiers.Control) && (k.KeyChar == 23))
{
Console.WriteLine("\b");
break;
}
if (k.Key == ConsoleKey.Enter)
{
Console.WriteLine("");
str += "\n";
}
ch = Convert.ToChar(k.KeyChar);
str += ch.ToString();
}
Console.WriteLine(str);
Console.Read();
}
}
}

Categories

Resources