C# foreach string with commas - c#

I have this code:
string[] neededFiles = {
"file1.exe",
"fille2.exe"
};
for (int file = 0; file != neededFiles.Length; file++)
{
if (!File.Exists(neededFiles[file]))
{
MessageBox.Show("App can't find this file - " + neededFiles[file]);
return;
}
}
Now when I launch my app it prints :
App can't find this file - file1.exe
App can't find this file - file2.exe
It's ok, but I wan't something like that:
App can't find this(-these) file(-files) - file1.exe, file2.exe
With what function / how can I do it? Is it possible? Thanks in advance

// using System.IO;
// using System.Windows.Forms;
// using System.Collections.Generics;
// using System.Linq;
IEnumerable<string> notFound = neededFiles.Where(f => !File.Exists(f));
if (notFound.Any())
MessageBox.Show(
string.Format(notFound.Count() > 1 ?
"App can't find these files - {0}" :
"App can't find this file - {0}",
string.Join(", ", notFound)));

Try this
string[] neededFiles = {
"file1.exe",
"fille2.exe"
};
string msg = string.Empty;
for (int file = 0; file != neededFiles.Length; file++)
{
if (!File.Exists(neededFiles[file]))
{
msg += neededFiles[file]+" ";
}
}
MessageBox.Show(" App can't find this(-these) file(-files) - " + msg);

Related

Using C# and MediaInfo How to detect HDR format

I'm using the MediaInfo Nuget Wrapper to analyse a bunch of files
using MediaInfo Actual on a file I can see
Video
ID : 1
Format : HEVC
Format/Info : High Efficiency Video Coding
Format profile : Main 10#L5.1#Main
HDR format : Dolby Vision, Version 1.0, dvhe.05.09, BL+RPU
Codec ID : dvhe
Codec ID/Info : High Efficiency Video Coding with Dolby Vision
This is also seen with Console.WriteLine(mw1.Inform());
However I'm unable to get that from the code below
I've tried HDR format, HDRformat and other speling but always returns ""
Given the fact that every file will be different is there a more dynamic way of doing this rather than hard coding each property?
Code still at testing stage
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using MediaInfo;
using MediaInfo.Model;
namespace GetMediaInfo
{
class Program
{
static void Main(string[] args)
{
string BaseFold = #"Path\To\Test\Samples";
string[] Files = Directory.GetFiles(BaseFold, "*.*", SearchOption.AllDirectories);
foreach (var Vid in Files)
{
string VidName = Path.GetFileName(Vid);
if (VidName.EndsWith("jpg"))
{
continue;
}
Console.WriteLine(VidName);
var mw1 = new MediaInfo.MediaInfo();
mw1.Option("ParseSpeed", "0");
mw1.Open(Vid);
string ToDisplay = "";
var videostreamcount = mw1.CountGet(StreamKind.Video, 0);
var AudioStreamcount = mw1.CountGet(StreamKind.Audio, 0);
if (videostreamcount > 0)
{
Console.WriteLine(mw1.Inform());
foreach (var item in mw1.Get(StreamKind.Video,0,"*"))
{
Console.WriteLine(item);
}
var Height = mw1.Get(StreamKind.Video, 0, "Height");
var Width = mw1.Get(StreamKind.Video, 0, "Width");
var VidFormat = mw1.Get(StreamKind.Video, 0, "Format");
var HDRformat = mw1.Get(StreamKind.Video, 0, "HDR format"); // Always = ""
var Codec = mw1.Get(StreamKind.Video, 0, "CodecID/Info");
var CodecID = mw1.Get(StreamKind.Video, 0, "CodecID");
Console.WriteLine("Height " + Height + ", Width " + Width + ", Codec " + Codec + ", CodecID " + CodecID + ", Format " + VidFormat + " , HDR format " + HDRformat);
ToDisplay += "\r\n\r\nInfo_Parameters\r\n";
ToDisplay += mw1.Option("Info_Parameters");
//ToDisplay += "\r\n\r\nInfo_Capacities\r\n";
//ToDisplay += mw1.Option("Info_Capacities");
//ToDisplay += "\r\n\r\nInfo_Codecs\r\n";
//ToDisplay += mw1.Option("Info_Codecs");
// Console.WriteLine(ToDisplay);
}
else
{
Console.WriteLine("Error No video streams in file");
}
if (AudioStreamcount > 0)
{
var AudioCodec = mw1.Get(StreamKind.Audio, 0, "CodecID/Info");
var AudioCodecID = mw1.Get(StreamKind.Audio, 0, "CodecID");
var AudioFormat = mw1.Get(StreamKind.Audio, 0, "Format");
Console.WriteLine("AudioCodec: {0}, AudioCodecID: {1}, AudioFormat {2}", AudioCodec, AudioCodecID, AudioFormat);
}
else
{
Console.WriteLine("Error No Audio streams in file");
}
}
Console.ReadLine();
}
}
}
Thanx
I've tried HDR format, HDRformat and other speling but always returns ""
HDR_Format
Tip: for knowing the keys to use, use MediaInfo command line with " --Language=raw" or graphical interface with XML output.
Jérôme, developer of MediaInfo

embed pcap dll files into c# project created DLL

I am trying to create user defined function which uses class defined in pcapDotNet.Core.Dll file. My c# Code is as below:
using System;
using System.IO;
using System.Collections.Generic;
using PcapDotNet.Core;
using System.Linq;
using System.Runtime.InteropServices;
using RGiesecke.DllExport; //GANESH
using System.Runtime.InteropServices;//GANESH
using System.Reflection;
namespace ObtainingAdvancedInformationAboutInstalledDevices
{
class Program1
{
/*
static void Main(string[] args)
{
Program1 var1 = new Program1();
var1.checkDevice();
}*/
public Program1()
{
AppDomain.CurrentDomain.AssemblyResolve += ResolveAssembly;
}
static Assembly ResolveAssembly(object sender, ResolveEventArgs args)
{
String dllName = new AssemblyName(args.Name).Name + ".dll";
var assem = Assembly.GetExecutingAssembly();
String resourceName = assem.GetManifestResourceNames().FirstOrDefault(rn => rn.EndsWith(dllName));
if (resourceName == null) return null; // Not found, maybe another handler will find it
using (var stream = assem.GetManifestResourceStream(resourceName))
{
Byte[] assemblyData = new Byte[stream.Length];
stream.Read(assemblyData, 0, assemblyData.Length);
return Assembly.Load(assemblyData);
}
}
//**************************************USER DEFINED FUNCTIONS START*********************
[DllExport("checkFunction", CallingConvention = CallingConvention.Cdecl)]//GANESH
public static int checkFunction()
{
Program1 worker1 = new Program1();
worker1.checkDevice();
return 0;
}
void checkDevice()
{
// Retrieve the interfaces list
IList<LivePacketDevice> allDevices = LivePacketDevice.AllLocalMachine;
Console.WriteLine(" inside checkDevice\n");
// Scan the list printing every entry
for (int i = 0; i != allDevices.Count(); ++i)
DevicePrint(allDevices[i]);
}
// Print all the available information on the given interface
private static void DevicePrint(IPacketDevice device)
{
// Name
Console.WriteLine(device.Name);
// Description
if (device.Description != null)
Console.WriteLine("\tDescription: " + device.Description);
// Loopback Address
Console.WriteLine("\tLoopback: " +
(((device.Attributes & DeviceAttributes.Loopback) == DeviceAttributes.Loopback)
? "yes"
: "no"));
// IP addresses
foreach (DeviceAddress address in device.Addresses)
{
Console.WriteLine("\tAddress Family: " + address.Address.Family);
if (address.Address != null)
Console.WriteLine(("\tAddress: " + address.Address));
if (address.Netmask != null)
Console.WriteLine(("\tNetmask: " + address.Netmask));
if (address.Broadcast != null)
Console.WriteLine(("\tBroadcast Address: " + address.Broadcast));
if (address.Destination != null)
Console.WriteLine(("\tDestination Address: " + address.Destination));
}
Console.WriteLine();
}
}
}
My python code is as below:
class gooseDriver():
"""A class that creates windows form by importing IED.MainWindow()"""
def __init__(self, ipAddress, port):
self.hllDll = WinDLL (r"C:\WORK\IEC61850\gooseThread1\gooseThread1\bin\x64\Debug\gooseThread1.dll")
self.hllDll.checkFunction()
print("Goose Message Started\n")
def main():
IED = gooseDriver("192.168.0.20", 102)
print("GooseDriver is called\n")
if __name__ == '__main__':
main()
when I tried to call checkFunction from python giving error as "OSError: [WinError -532462766] Windows Error 0xe0434352". This is because function is using LivePacketsDevice class from pcap files. I have embedded pcapDotNet.Core.Dll file while generating DLL as reference. Can anybody suggest what is solution for this issue please.
After lot of trial, it started working when i placed pcapDotNet DLL files into folder where Python interpreter exists. Dont know what is reason? can anybody know on this please.

C# System.IO.IOException

I have following code:
using System;
using System.Collections.Generic;
using System.IO;
using VirusTotalNET;
using VirusTotalNET.Objects;
using System.Linq;
using System.Security.Permissions;
namespace VirusTotalNETClient
{
class Program
{
private const string ScanUrl = "http://www.google.com/";
static void Main(string[] args)
{
VirusTotal virusTotal = new VirusTotal("5d8684f50946c2bdeaf5c4fd966f61f3661de808e9d7324b99788d6f4fb7ad57");
//Use HTTPS instead of HTTP
virusTotal.UseTLS = true;
//creating folder for programs reliqies and output log
string folderName = "C:\\OnlineScanner";
System.IO.Directory.CreateDirectory(folderName);
//get list of files to analyse
var paths = Traverse("C:\test");
File.WriteAllLines("C:\\OnlineScanner\\test.txt", paths);
foreach (string line in File.ReadLines("C:\\test.txt"))
{
//Define what file you want to analyse
FileInfo fileInfo = new FileInfo(line);
//Check if the file has been scanned before.
FileReport fileReport = virusTotal.GetFileReport(fileInfo);
bool hasFileBeenScannedBefore = fileReport.ResponseCode == ReportResponseCode.Present;
//If the file has been scanned before, the results are embedded inside the report.
if (hasFileBeenScannedBefore)
{
int detekce = fileReport.Positives;
if (detekce >= 1)
{
using (var writer = new StreamWriter("C:\\OnlineScanner\\OnlineScannerLog.txt"))
{
writer.WriteLine(line);
writer.WriteLine("URL to test: " + fileReport.Permalink);
writer.WriteLine("Detect ratio: " + fileReport.Positives + "/54");
writer.WriteLine("Message: " + fileReport.VerboseMsg);
writer.WriteLine();
writer.WriteLine();
}
}
System.Threading.Thread.Sleep(16000);
}
else
{
ScanResult fileResult = virusTotal.ScanFile(fileInfo);
int detekce = fileReport.Positives;
if (detekce >= 1)
{
using (var writer = new StreamWriter("C:\\OnlineScanner\\OnlineScannerLog.txt"))
{
writer.WriteLine(line);
writer.WriteLine("URL to test: " + fileReport.Permalink);
writer.WriteLine("Detect ratio: " + fileReport.Positives + "/54");
writer.WriteLine("Message: " + fileReport.VerboseMsg);
writer.WriteLine();
writer.WriteLine();
}
}
System.Threading.Thread.Sleep(16000);
}
}
}
private static IEnumerable<string> Traverse(string rootDirectory)
{
IEnumerable<string> files = Enumerable.Empty<string>();
IEnumerable<string> directories = Enumerable.Empty<string>();
try
{
// The test for UnauthorizedAccessException.
var permission = new FileIOPermission(FileIOPermissionAccess.PathDiscovery, rootDirectory);
permission.Demand();
files = Directory.GetFiles(rootDirectory);
directories = Directory.GetDirectories(rootDirectory);
}
catch
{
// Ignore folder (access denied).
rootDirectory = null;
}
foreach (var file in files)
{
yield return file;
}
// Recursive call for SelectMany.
var subdirectoryItems = directories.SelectMany(Traverse);
foreach (var result in subdirectoryItems)
{
yield return result;
}
}
}
}
This code run some time (arround 15secs) but then program crashs.
The error is
System.IO.IOException, process can't access to file C:\hiberfil.sys.
http://upnisito.cz/images/2016_12/319crasherrror.png
Do you have any idea how to solve it?

StreamWriter stops in the middle of a WriteLine

I have a small application that checks all of the logs in a directory named after domain usernames and generates a results file with each username and the relevant first and surname for that user.
The console is outputting the full list successfully but it seems that the StreamWriter is stopping halfway through an entry.
The number of characters it writes before stopping is consistent - to some extent. If I set the outputstring to include more characters between the two variables filename and the result from FindNameFromUsername then the character count with or without spaces changes so I've ruled that out.
Any ideas as to why the console outputs the line but the streamwriter doesn't?
Code below:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Threading.Tasks;
using System.DirectoryServices;
using System.DirectoryServices.AccountManagement;
using System.DirectoryServices.ActiveDirectory;
namespace Filename_Finder
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Please insert the full directory path. All filenames in the root of this folder will be logged to one file.");
string outputFilename = "results.txt";
string userPath = Console.ReadLine();
string domain = "ou=users,dc=domain,dc=local";
try
{
string outputFilepath = userPath + outputFilename;
string[] filepaths = Directory.GetFiles(userPath);
using (StreamWriter file = new StreamWriter(outputFilepath, false))
{
for (int i = 0; i < filepaths.Length; i++)
{
string filepath = filepaths[i];
char split = '.';
string filename = filepath.Remove(0, userPath.Count());
if (filename != outputFilename)
{
int extensionBegins = filename.LastIndexOf(split);
filename = filename.Remove(extensionBegins);
string outputstring = (filename + " -- " + FindNameFromUsername(filename, domain));
Console.WriteLine(outputstring);
file.WriteLine(outputstring);
}
}
Console.ReadLine();
}
}
catch (Exception e) { Console.WriteLine(e); Console.ReadLine(); }
}
public static string FindNameFromUsername(string username, string domainScope)
{
string connectionPrefix = "LDAP://" + domainScope;
DirectoryEntry entry = new DirectoryEntry(connectionPrefix);
DirectorySearcher searcher = new DirectorySearcher(entry);
string filter = "(&(objectClass=user)";
filter += "(|(sAMAccountName=" + username + ")))";
searcher.Filter = filter;
SearchResult result = searcher.FindOne();
string resultValue = string.Empty;
DirectoryEntry obj = result.GetDirectoryEntry();
resultValue = "" + obj.Properties["givenName"].Value + " " + obj.Properties["sn"].Value;
if (resultValue == " ") { resultValue = username; }
entry.Close(); entry.Dispose();
obj.Close(); obj.Dispose();
searcher.Dispose();
return resultValue;
}
}
}
Your Console.ReadLine() will pause the execution and I'm guessing that's where you are checking the content of your file.
However, the file won't be flushed and closed until the StreamWriter is being disposed. That happens at the end of the using block, i.e. after your ReadLine() statement.
Take a look at this question.
You might find useful setting your StreamWriter.AutoFlush property to true in order to get similar behavior to the corresponding Console method, like this:
using (var file = new StreamWriter(outputFilepath, false) { AutoFlush = true })

Move files in C#

I am moving some images (filenames are(1).PNG, (2).PNG and so on) from one directory to another. I am using the following code:
for (int i = 1; i < n; i++)
{
try
{
from = "E:\\vid\\(" + i + ").PNG";
to = "E:\\ConvertedFiles\\" + i + ".png";
File.Move(from, to); // Try to move
Console.WriteLine("Moved"); // Success
}
catch (IOException ex)
{
Console.WriteLine(ex); // Write error
}
}
However, I am getting the following error:
A first chance exception of type System.IO.FileNotFoundException occurred in mscorlib.dll
System.IO.FileNotFoundException: Could not find file 'E:\vid\(1).PNG'.
Also, I am planning to rename the files so that the converted file name will be 00001.png, 00002.png, ... 00101.png and so on.
I suggest you to use '#' in order to escape slashes in a more readable way. Use also Path.Combine(...) in order to concatenate paths and PadLeft in order to have your filenames as your specifics.
for (int i = 1; i < n; i++)
{
try
{
from = System.IO.Path.Combine(#"E:\vid\","(" + i.ToString() + ").PNG");
to = System.IO.Path.Combine(#"E:\ConvertedFiles\",i.ToString().PadLeft(6,'0') + ".png");
File.Move(from, to); // Try to move
Console.WriteLine("Moved"); // Success
}
catch (IOException ex)
{
Console.WriteLine(ex); // Write error
}
}
Why don't you use something like this?
var folder = new DirectoryInfo(#"E:\vid\"));
if (folder.Exists)
{
var files = folder.GetFiles(".png");
files.toList().ForEach(f=>File.Move(from,to));
}
The exception means that the file E:\vid(1).PNG doesn't exist. Do you mean E:\vid1.PNG?
Use System.IO.Path class for constructing paths, it's better than concatenating strings. You don't have to worry about escapting backslashes.
I just ran this in Visual Studio. It worked.
using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication2
{
class Program
{
static void Main()
{
int n = 3;
for (int i = 1; i < n; i++)
{
string from = "C:\\vid\\(" + i + ").PNG";
string to = "C:\\ConvertedFiles\\" + i + ".png";
{
try
{
File.Move(from, to); // Try to move
Console.WriteLine("Moved"); // Success
}
catch (System.IO.FileNotFoundException e)
{
Console.WriteLine(e); // Write error
}
}
}
}
}
}
Maybe when you were moving files into vid directory to begin the test, windows shaved off the parenthesis. (1).png became 1.png... I got a file not found error from that phenomenon... otherwise, your code is solid. My version is almost identical.
i.ToString()
might help you. You are passing
from = "E:\\vid\\(" + i + ").PNG";
to = "E:\\ConvertedFiles\\" + i + ".png";
I as integer and concatenation doesn't work due to that
and instead of using \\, add # like this
from = #"E:\vid\(" + i + ").PNG";
var folder = new DirectoryInfo(sourcefolder);
if (folder.Exists)
{
var files = folder.GetFiles("*.png");
files.ToList().ForEach(f => File.Move(sourcefolder + f, newFolderName + f));
}
I believe this will help.

Categories

Resources