How can i impove my code? - c#

Because I have no experience with sockets and I don't know how to make one, I have this code:
public void getGameInfo()
{
string content;
do
{
WebClient client = new WebClient();
client.DownloadFile(fileadress, filename);
client.Dispose();
StreamReader reader = new StreamReader(filename);
content = reader.ReadToEnd();
reader.Close();
} while (content == "");
File.Delete(filename);
string[] lines = content.Split(separator, StringSplitOptions.RemoveEmptyEntries);
mode = zeilen[0];
gameInfo = new string[line.Length-1];
Array.Copy(lines, 1, gameInfo, 0, lines.Length-1);
}
It connects to a Apache server with a .txt file and reads it. But if too many Programms (three) uses the code, it will throw a WebException.
So is there a way to improve this, or a guide to make a socket for this?
Edit 1:
And what if I want to write to the file like this function?
public void setSpielInfo(int line, string input)
{
WebClient client = new WebClient();
string content;
do
{
client.DownloadFile(gameadress, filename);
StreamReader reader = new StreamReader(filename);
content = reader.ReadToEnd();
reader.Close();
} while (content == "");
string[] lines = content.Split(separator, StringSplitOptions.RemoveEmptyEntries);
lines[zeile+1] = input;
byte[] bytearray = Encoding.ASCII.GetBytes(string.Join(Environment.NewLine, lines)); // I've read that byte arrays are faster than string arrays
FileStream writer = new FileStream(filename, FileMode.Truncate);
writer.Write(bytearray, 0, bytearray.Length);
writer.Close();
client.UploadFile(ftpAdress, filename);
client.Dispose();
File.Delete(filename);
}

You want to read string, right? So why do you download file?
string content;
// Do not dispose explicitly, wrap into using instead
using (WebClient client = new WebClient()) {
content = client.DownloadString(fileadress);
}
string[] lines = content.Split(separator, StringSplitOptions.RemoveEmptyEntries);
mode = lines.FirstOrDefault(); // 1st line
gameInfo = lines.Skip(1).ToArray(); // all the others
You can further shorten the code into
using (WebClient client = new WebClient()) {
var lines = client
.DownloadString(fileadress)
.Split(separator, StringSplitOptions.RemoveEmptyEntries);
mode = lines.FirstOrDefault();
gameInfo = lines.Skip(1).ToArray();
}
Edit: again, what do you actually want to perform: download a string, write file, upload the file:
string content;
// Do not dispose explicitly, wrap into using instead
using (WebClient client = new WebClient()) {
// Download string (text)
content = client.DownloadString(fileadress);
// Write the text to file (override existing if it is)
File.WriteAllText(filename, content);
// Upload file
// think on uploading the string - client.UploadString(ftpAdress, content);
client.UploadFile(ftpAdress, filename);
}
string[] lines = content.Split(separator, StringSplitOptions.RemoveEmptyEntries);
mode = lines.FirstOrDefault(); // 1st line
gameInfo = lines.Skip(1).ToArray(); // all the others
As the further improvent think on working with string not files:
using (WebClient client = new WebClient()) {
// Download string (text)
content = client.DownloadString(fileadress);
client.UploadString(ftpAdress, content);
}

Related

StreamReader save ReadLine to string and use it in if

Hi I want to save the output from reader.ReadToEnd() to a string and check if the string is "Access" but I don't know how to do it.
string url = "https://mywebsite.com/check.php";
Stream mystream = client.OpenRead(url);
StreamReader reader = new StreamReader(mystream);
Console.WriteLine(reader.ReadToEnd()); //The text will be "Access"
//Pseudecode start
string line = reader.ReadToEnd();
if (line == "Access")
{
useraccess = true;
Console.WriteLine("Done!");
}
mystream.Close();
You are reading the stream twice without any sort of reset, it would be more advisable to read it only once. Also you should be disposing of your stream and streamreader appropriately. See the following:
string url = "https://mywebsite.com/check.php";
string remoteData = null;
using (Stream mystream = client.OpenRead(url))
using (StreamReader reader = new StreamReader(mystream))
remoteData = reader.ReadToEnd();
Console.WriteLine(remoteData); //The text will be "Access"
//Pseudecode start
if (remoteData == "Access")
{
useraccess = true;
Console.WriteLine("Done!");
}
This should work under the assumption that ReadToEnd() is returning what you wanted it to return. I don't know what your endpoint looks like so I can't verify.

Read last line from website without saving file on disk

I have a website with many large CSV files (up to 100,000 lines each). From each CSV file, I need to read the last line in the file. I know how to solve the problem when I save the file on disk before reading its content:
var url = "http://data.cocorahs.org/cocorahs/export/exportreports.aspx?ReportType=Daily&Format=csv&Date=1/1/2000&Station=UT-UT-24"
var client = new System.Net.WebClient();
var tempFile = System.IO.Path.GetTempFileName();
client.DownloadFile(url, tempFile);
var lastLine = System.IO.File.ReadLines(tempFile).Last();
Is there any way to get the last line without saving a temporary file on disk?
I tried:
using (var stream = client.OpenRead(seriesUrl))
{
using (var reader = new StreamReader(stream))
{
var lastLine = reader.ReadLines("file.txt").Last();
}
}
but the StreamReader class does not have a ReadLines method ...
StreamReader does not have a ReadLines method, but it does have a ReadLine method to read the next line from the stream. You can use it to read the last line from the remote resource like this:
using (var stream = client.OpenRead(seriesUrl))
{
using (var reader = new StreamReader(stream))
{
string lastLine;
while ((lastLine = reader.ReadLine()) != null)
{
// Do nothing...
}
// lastLine now contains the very last line from reader
}
}
Reading one line at a time with ReadLine will use less memory compared to StreamReader.ReadToEnd, which will read the entire stream into memory as a string. For CSV files with 100,000 lines this could be a significant amount of memory.
This worked for me, though the service did not return data (Headers of CSV only):
public void TestMethod1()
{
var url = "http://data.cocorahs.org/cocorahs/export/exportreports.aspx?ReportType=Daily&Format=csv&Date=1/1/2000&Station=UT-UT-24";
var client = new System.Net.WebClient();
using (var stream = client.OpenRead(url))
{
using (var reader = new StreamReader(stream))
{
var str = reader.ReadToEnd().Split('\n').Where(x => !string.IsNullOrEmpty(x)).LastOrDefault();
Debug.WriteLine(str);
Assert.IsNotEmpty(str);
}
}
}

Asp .NET Read a file from a tar.gz archive

I have some files inside in one .tar.gz archive. These files are on a linux server.How can I read from a specific file inside this archive if I know it's name?
For reading direct from the txt file, I used the following code:
Uri urlFile = new Uri("ftp://" + ServerName + "/%2f" + FilePath + "/" + fileName);
WebClient req = new WebClient() { Credentials=new NetworkCredential("user","psw")};
string result = req.DownloadString(urlFile);
It's possible to read this file without copying the archive on the local machine, something like the code above?
I found a solution. Maybe this can help you guys.
// archivePath="ftp://myLinuxServer.com/%2f/move/files/archive/20170225.tar.gz";
public static string ExtractFileFromArchive(string archivePath, string fileName)
{
string stringFromFile="File not found";
WebClient wc = new WebClient() { Credentials = cred, Proxy= webProxy }; //Create webClient with all necessary settings
using (Stream source = new GZipInputStream(wc.OpenRead(archivePath))) //wc.OpenRead() create one stream with archive tar.gz from our server
{
using (TarInputStream tarStr =new TarInputStream(source)) //TarInputStream is a stream from ICSharpCode.SharpZipLib.Tar library(need install SharpZipLib in nutgets)
{
TarEntry te;
while ((te = tarStr.GetNextEntry())!=null) // Go through all files from archive
{
if (te.Name == fileName)
{
using (Stream fs = new MemoryStream()) //Create a empty stream that we will be fill with file contents.
{
tarStr.CopyEntryContents(fs);
fs.Position = 0; //Move stream position to 0, in order to read from beginning
stringFromFile = new StreamReader(fs).ReadToEnd(); //Convert stream to string
}
break;
}
}
}
}
return stringFromFile;
}

Change a line in a file containing a specific String in C#

ive got a problem: i want to find a line containing a certain string, but i only know how to replace the string in the file or all the lines, i know the command "string.Contains", but it doesnt seem to work properly as i use it: i tried to use "if (data.contains(string))", but then it still changes all the lines to that string. heres my code:
private void button1_Click(object sender, EventArgs e)
{
string replaceText = "peter";
string withText = "Gilbert";
using (System.IO.StreamReader streamReader = new System.IO.StreamReader(#"C:\Users\G\Documents\test.txt"))
{
using (System.IO.StreamWriter streamWriter = new System.IO.StreamWriter(#"C:\Users\G\Documents\test.txt" + ".tmp"))
{
while (!streamReader.EndOfStream)
{
string data = streamReader.ReadLine();
data = data.Replace(replaceText, withText);
streamWriter.WriteLine(data);
}
}
}
using (System.IO.StreamReader streamReader = new System.IO.StreamReader(#"C:\Users\G\Documents\test.txt" + ".tmp"))
{
using (System.IO.StreamWriter streamWriter = new System.IO.StreamWriter(#"C:\Users\G\Documents\test.txt"))
{
while (!streamReader.EndOfStream)
{
string data = streamReader.ReadLine();
data = data.Replace(replaceText, withText);
streamWriter.WriteLine(data);
}
}
}
}
}
Try this:
FileStream stream = File.Open("file", FileMode.Open);
StreamReader rdr = new StreamReader(rdr);
String[] flines = rdr.ReadToEnd().Split(new String[]{"\r\n"}, StringSplitOptions.None);
rdr.Close();
stream = File.Create("file");
StreamWriter wtr = new StreamWriter(stream);
foreach(String str in flines)
{
wtr.WriteLine(str.Replace(replaceTxt, newText));
}
wtr.Close();
Of course you could put logic in the loop the either change or not change the string written based on whatever criterion you like.

File upload in asp.net c#

hey guys, m using an api of "Bits on the Run" following is the code of upload API
public string Upload(string uploadUrl, NameValueCollection args, string filePath)
{
_queryString = args; //no required args
WebClient client = createWebClient();
_queryString["api_format"] = APIFormat ?? "xml"; //xml if not specified - normally set in required args routine
queryStringToArgs();
string callUrl = _apiURL + uploadUrl + "?" + _args;
callUrl = uploadUrl + "?" + _args;
try {
byte[] response = client.UploadFile(callUrl, filePath);
return Encoding.UTF8.GetString(response);
} catch {
return "";
}
}
and below is my code to upload a file, m using FileUpload control to get the full path of a file(but m not succeeded in that)...
botr = new BotR.API.BotRAPI("key", "secret_code");
var response = doc.Descendants("link").FirstOrDefault();
string url = string.Format("{0}://{1}{2}", response.Element("protocol").Value, response.Element("address").Value, response.Element("path").Value);
//here i want fullpath of the file, how can i achieve that here
string filePath = fileUpload.PostedFile.FileName;//"C://Documents and Settings//rkrishna//My Documents//Visual Studio 2008//Projects//BitsOnTheRun//BitsOnTheRun//rough_test.mp4";
col = new NameValueCollection();
FileStream fs = new FileStream(filePath, FileMode.Open);
col["file_size"] = fs.Length.ToString();
col["file_md5"] = BitConverter.ToString(HashAlgorithm.Create("MD5").ComputeHash(fs)).Replace("-", "").ToLower();
col["key"] = response.Element("query").Element("key").Value;
col["token"] = response.Element("query").Element("token").Value;
fs.Dispose();
string uploadResponse = botr.Upload(url, col, filePath);
i read in some forums saying that for some security purpose you can't get fullpath of a file from client side. If it is true then how can i achieve file upload in my scenario ?
Yes, this is true, for security reason you cannot get the fullpath of the client machine, what you can do is, try the following,
Stream stream = fileUpload.PostedFile.InputStream;
stream.Read(bytes, 0, fileUpload.PostedFile.ContentLength);
instead of creating your own FileStream use the stream provided by the FileUploadControl. Hoep it shall help.

Categories