Meistro
Meistro
CC#
Created by Meistro on 4/24/2023 in #help
❔ Random take a File from a Folder
Hello Dear CSharp Programmers I have a Question, lets say I have a folder with 1_000 Files. From this folder I would like to randomly pick 1_00. But every file should be taken only once. How would this method look like ? I tryed it by myself but it always take one file more then once. my Code:
static public int RandomNumber;
static public int randomIndex;
static Random random = new Random(DateTime.Now.Millisecond);;

public string GetRadomFileFromGivenFolderPath()
{
if (FolderPath_RandomFiles.Text != " ")
{
// Get an array of all file paths in the specified folder
string[] files = Directory.GetFiles(FolderPath_RandomFiles.Text);

// If no files are found, return null
if (files.Length == 0)
{
UpdateRichTextBox("No Files found!");
return "null";
}

// Generate a random number between 0 and the number of files minus 1
do
{
// Generate a random number between 0 and the number of files minus 1
randomIndex = random.Next(0, files.Length - 1);

} while (RandomNumber == randomIndex);

RandomNumber = randomIndex;
// Return the file path at the random index
return RandomFilePath = files[randomIndex];
}
else
{
UpdateRichTextBox("Folder path for \"random Files Path\" not found!");
return "null";
}
}
static public int RandomNumber;
static public int randomIndex;
static Random random = new Random(DateTime.Now.Millisecond);;

public string GetRadomFileFromGivenFolderPath()
{
if (FolderPath_RandomFiles.Text != " ")
{
// Get an array of all file paths in the specified folder
string[] files = Directory.GetFiles(FolderPath_RandomFiles.Text);

// If no files are found, return null
if (files.Length == 0)
{
UpdateRichTextBox("No Files found!");
return "null";
}

// Generate a random number between 0 and the number of files minus 1
do
{
// Generate a random number between 0 and the number of files minus 1
randomIndex = random.Next(0, files.Length - 1);

} while (RandomNumber == randomIndex);

RandomNumber = randomIndex;
// Return the file path at the random index
return RandomFilePath = files[randomIndex];
}
else
{
UpdateRichTextBox("Folder path for \"random Files Path\" not found!");
return "null";
}
}
I wanted to also store all ever picked Files and always check if the newly picked random file has already used once or not but I couldnt manage to code it. thank you for every help
19 replies
CC#
Created by Meistro on 4/24/2023 in #help
Random pick a file from a given Folder
Hello Dear CSharp Programmers I have a Question, lets say I have a folder with 1_000 Files. From this folder I would like to randomly pick 1_00. But every file should be taken only once. How would this method look like ? I tryed it by myself but it always take one file more then once. my Code:
static public int RandomNumber;
static public int randomIndex;
static Random random = new Random(DateTime.Now.Millisecond);;

public string GetRadomFileFromGivenFolderPath()
{
if (FolderPath_RandomFiles.Text != " ")
{
// Get an array of all file paths in the specified folder
string[] files = Directory.GetFiles(FolderPath_RandomFiles.Text);

// If no files are found, return null
if (files.Length == 0)
{
UpdateRichTextBox("No Files found!");
return "null";
}

// Generate a random number between 0 and the number of files minus 1
do
{
// Generate a random number between 0 and the number of files minus 1
randomIndex = random.Next(0, files.Length - 1);

} while (RandomNumber == randomIndex);

RandomNumber = randomIndex;
// Return the file path at the random index
return RandomFilePath = files[randomIndex];
}
else
{
UpdateRichTextBox("Folder path for \"random Files Path\" not found!");
return "null";
}
}
static public int RandomNumber;
static public int randomIndex;
static Random random = new Random(DateTime.Now.Millisecond);;

public string GetRadomFileFromGivenFolderPath()
{
if (FolderPath_RandomFiles.Text != " ")
{
// Get an array of all file paths in the specified folder
string[] files = Directory.GetFiles(FolderPath_RandomFiles.Text);

// If no files are found, return null
if (files.Length == 0)
{
UpdateRichTextBox("No Files found!");
return "null";
}

// Generate a random number between 0 and the number of files minus 1
do
{
// Generate a random number between 0 and the number of files minus 1
randomIndex = random.Next(0, files.Length - 1);

} while (RandomNumber == randomIndex);

RandomNumber = randomIndex;
// Return the file path at the random index
return RandomFilePath = files[randomIndex];
}
else
{
UpdateRichTextBox("Folder path for \"random Files Path\" not found!");
return "null";
}
}
I wanted to also store all ever picked Files and always check if the newly picked random file has already used once or not but I couldnt manage to code it. thank you for every help
1 replies
CC#
Created by Meistro on 4/18/2023 in #help
❔ multithreading with Tasks
I have a question about C# multithreading or async methods. I'm currently trying to upload multiple files to a server via an API (with login data, etc.). My problem is that while waiting for all the tasks to complete, I want to query how many tasks have already finished, as long as the tasks are not yet completed. Specifically, I am uploading 30k files. Each file is started as a task. While the tasks are running, a loop should run during the await (await Task.WhenAll(uploadTasks);) to check how many tasks have already completed, and every 10k files, there should be a message like "Hey, I have uploaded 10k files and it's still running."
//<--- there is a code for the task above that runs all task

await Task.WhenAll(uploadTasks);

//decides how often should the system give a feedback every 10000 Files
runnerctr = 0;

//10.000 steps
int runner = 0;

// Loop that checks out hwo is process doing
while (runner < int.Parse(File_Upload_Count_Simu.Text))
{
//wait for some time before updating
await Task.Delay(TimeSpan.FromSeconds(5));

// loop through all tasks and update the counter for all done uploads(tasks)
foreach (var task in uploadTasks)
{
if (task.IsCompleted)
{
runner++;
}
}
// get progress every 10000 tasks which are done
if (runner >= runnerctr + 10000)
{
runnerctr += 10000;
UpdateRichTextBox("do something");
}
}
//<--- there is a code for the task above that runs all task

await Task.WhenAll(uploadTasks);

//decides how often should the system give a feedback every 10000 Files
runnerctr = 0;

//10.000 steps
int runner = 0;

// Loop that checks out hwo is process doing
while (runner < int.Parse(File_Upload_Count_Simu.Text))
{
//wait for some time before updating
await Task.Delay(TimeSpan.FromSeconds(5));

// loop through all tasks and update the counter for all done uploads(tasks)
foreach (var task in uploadTasks)
{
if (task.IsCompleted)
{
runner++;
}
}
// get progress every 10000 tasks which are done
if (runner >= runnerctr + 10000)
{
runnerctr += 10000;
UpdateRichTextBox("do something");
}
}
it is working by the way ...but I am not sure whether it is realy counting while awating or not.
127 replies
CC#
Created by Meistro on 3/21/2023 in #help
Newtonsoft.Json.JsonReaderException: "Unexpected character encountered while parsing value: <. Path
Hei all, I am coding a REST API HTTP POST REQUEST, but I always get an error as soon as I start Building the Project. Might it be the way how my JSON is written ? or maybe something else ? the code:
static private void RunAsyncPost(string username, string password)
{
string url = "http://someIP/rest";

// Create the JSON request body
var requestBody = new
{
info = new
{
name = "C#testfile.js",
type = 282,
isDir = false,
desc = "",
@lock = "",
ownerName = "Some Service",
access = "WDDRWDE-PIDDS",
parentId = 234253
},
acl = new[]
{
new
{
member = "Administrator",
id = 0,
type = "USER",
access = "RWWEDSGEERLP"
}
},
keywording = new
{
maskNameOriginal = "Incoming Invoice",
fields = new
{
VENDOR_NAME = "Test_Vendor1"
}
}
};

// Serialize the JSON request body
string jsonRequestBody = JsonConvert.SerializeObject(requestBody);

// Create the HTTP client and request message
using (var httpClient = new HttpClient())
using (var requestMessage = new HttpRequestMessage(HttpMethod.Post, url))
{
// Set the authorization header
string authHeader = "Basic " + Convert.ToBase64String(System.Text.Encoding.ASCII.GetBytes($"{username}:{password}"));
requestMessage.Headers.Authorization = new AuthenticationHeaderValue("Authorization", authHeader);

// Set the content type and request body
requestMessage.Content = new StringContent(jsonRequestBody, System.Text.Encoding.UTF8, "application/json");

// Send the HTTP request and get the response
var response = httpClient.SendAsync(requestMessage).Result;

// Check the response status code
if (response.IsSuccessStatusCode)
{
// Deserialize the response body
//var responseBody = JsonConvert.DeserializeObject(response.Content.ReadAsStringAsync().Result);
var responseBody = JsonConvert.DeserializeObject<string>(response.Content.ReadAsStringAsync().Result);
// Do something with the response
ResponseStream = responseBody.ToString(); // output normaly in CMD but here I am using a textbox of windows Forms
}
else
{
ResponseStream = $"HTTP error {response.StatusCode}"; // output normaly in CMD but here I am using a textbox of windows Forms
}
}
static private void RunAsyncPost(string username, string password)
{
string url = "http://someIP/rest";

// Create the JSON request body
var requestBody = new
{
info = new
{
name = "C#testfile.js",
type = 282,
isDir = false,
desc = "",
@lock = "",
ownerName = "Some Service",
access = "WDDRWDE-PIDDS",
parentId = 234253
},
acl = new[]
{
new
{
member = "Administrator",
id = 0,
type = "USER",
access = "RWWEDSGEERLP"
}
},
keywording = new
{
maskNameOriginal = "Incoming Invoice",
fields = new
{
VENDOR_NAME = "Test_Vendor1"
}
}
};

// Serialize the JSON request body
string jsonRequestBody = JsonConvert.SerializeObject(requestBody);

// Create the HTTP client and request message
using (var httpClient = new HttpClient())
using (var requestMessage = new HttpRequestMessage(HttpMethod.Post, url))
{
// Set the authorization header
string authHeader = "Basic " + Convert.ToBase64String(System.Text.Encoding.ASCII.GetBytes($"{username}:{password}"));
requestMessage.Headers.Authorization = new AuthenticationHeaderValue("Authorization", authHeader);

// Set the content type and request body
requestMessage.Content = new StringContent(jsonRequestBody, System.Text.Encoding.UTF8, "application/json");

// Send the HTTP request and get the response
var response = httpClient.SendAsync(requestMessage).Result;

// Check the response status code
if (response.IsSuccessStatusCode)
{
// Deserialize the response body
//var responseBody = JsonConvert.DeserializeObject(response.Content.ReadAsStringAsync().Result);
var responseBody = JsonConvert.DeserializeObject<string>(response.Content.ReadAsStringAsync().Result);
// Do something with the response
ResponseStream = responseBody.ToString(); // output normaly in CMD but here I am using a textbox of windows Forms
}
else
{
ResponseStream = $"HTTP error {response.StatusCode}"; // output normaly in CMD but here I am using a textbox of windows Forms
}
}
Thanks in advance for any help 🙂
24 replies
CC#
Created by Meistro on 10/25/2022 in #help
System.UnauthorizedAccessException [Answered]
Hei I need help with this line
foreach (string valid_path in Directory.EnumerateDirectories(dir, validFolderName, SearchOption.AllDirectories))
foreach (string valid_path in Directory.EnumerateDirectories(dir, validFolderName, SearchOption.AllDirectories))
I want to search for a specific Folder in my Drive "C:\" But it always give me access denie for C:$Recycle.Bin. I want to skip it but it doesnt work even with try cath. Thanks for any help
15 replies
CC#
Created by Meistro on 10/17/2022 in #help
denied accessing path string[] list1 = Directory.GetFiles(C_Drive, *.exe, SearchOption.AllDirectorie
Hei all, I am not able to iterate through my drive ... is it a security problem ? I already opened VS as Admin ERROR Message:
Unhandled exception. System.UnauthorizedAccessException: Access to the path 'C:\Documents and Settings' is denied.
at System.IO.Enumeration.FileSystemEnumerator`1.CreateRelativeDirectoryHandle(ReadOnlySpan`1 relativePath, String fullPath)
at System.IO.Enumeration.FileSystemEnumerator`1.MoveNext()
at System.Collections.Generic.LargeArrayBuilder`1.AddRange(IEnumerable`1 items)
at System.Collections.Generic.EnumerableHelpers.ToArray[T](IEnumerable`1 source)
at System.Linq.Enumerable.ToArray[TSource](IEnumerable`1 source)
Unhandled exception. System.UnauthorizedAccessException: Access to the path 'C:\Documents and Settings' is denied.
at System.IO.Enumeration.FileSystemEnumerator`1.CreateRelativeDirectoryHandle(ReadOnlySpan`1 relativePath, String fullPath)
at System.IO.Enumeration.FileSystemEnumerator`1.MoveNext()
at System.Collections.Generic.LargeArrayBuilder`1.AddRange(IEnumerable`1 items)
at System.Collections.Generic.EnumerableHelpers.ToArray[T](IEnumerable`1 source)
at System.Linq.Enumerable.ToArray[TSource](IEnumerable`1 source)
Thanks in Advance for any Help 🙂
7 replies
CC#
Created by Meistro on 10/11/2022 in #help
Project wont run
Executable in debug won´t run when moving project folder to another location
7 replies
CC#
Created by Meistro on 10/10/2022 in #help
Hei all, I am new to this Server and I realy need help on specific Problem [Answered]
I am trying to move a .csv File from a Folder to another and it is actualy working but when I open the transfered File and compare it with the original one, the new File seem to be completly different. It is broken. There are new Characters in the new file which are not existing in the Origin one. Thanks in advance
102 replies