My code:
public static string Source = #"\\192.168.181.1\Z$\z";
public static string Destination = #"\\192.168.181.1\Z$\z_rar\" + DateTime.Now.ToString("dddd");
public static string Extension = #".zip";
private static void Main(string[] args)
{
if (File.Exists(Destination + Extension))
try
{
File.Delete(Destination + Extension);
ZipFile.CreateFromDirectory(Source, Destination + Extension, CompressionLevel.NoCompression, false);
// here: zipped file details in txt file
}
catch (IOException e)
{
Console.WriteLine(e.Message);
}
else
ZipFile.CreateFromDirectory(Source, Destination + Extension, CompressionLevel.NoCompression, false);
}
How can i create zipped files details save to zipfilename_log.txt file (line by line) in same directory after zipfile.createfromdirectory ?
I solved the problem with the below code:
public static string Source = #"\\192.168.1.11\Z$\z";
public static string Destination = #"\\192.168.1.11\Z$\z_rar\";
public static string NameFormat = DateTime.Now.ToString("dddd");
public static string Extension = #".zip";
public static string LogFilePath = Destination + NameFormat + "_log.txt";
private static void Main(string[] args)
{
File.Delete(Destination + NameFormat + Extension);
File.Delete(LogFilePath);
try
{
ZipFile.CreateFromDirectory(Source, Destination + NameFormat + Extension,
CompressionLevel.NoCompression, false);
var fileListBuilder = new StringBuilder();
using (var za = ZipFile.OpenRead(Destination + NameFormat + Extension))
{
foreach (var zae in za.Entries) fileListBuilder.AppendLine(zae.FullName);
}
File.WriteAllText(LogFilePath, fileListBuilder.ToString());
}
catch (IOException e)
{
File.WriteAllText(LogFilePath, e.ToString());
}
}
Output:
file1.exe
file5.exe
Folder1
Folder2\file3.pdf
Folder2\file4.msi
Thanks to everyone who replies.
Related
If I have my class
public class File
{
public bool Load(string fileName)
bool returnValue = false;
if (File.Exists(fileName))
{
returnValue = true;
Logger.Info("File found.");
}
else
{
Logger.Error("File does not exists.");
}
return returnValue;
}
I tried in my main Program.cs
class Program
{
static void Main(string[] args)
{
var appender = new log4net.Appender.MemoryAppender();
log4net.Config.BasicConfigurator.Configure(appender);
var logEntries = appender.GetEvents();
File file = new File();
string folderPath = #"C:\User\files\";
string[] files = Directory.GetFiles(folderPath, "*.*", SearchOption.AllDirectories);
foreach(string oneFile in files)
{
file.Load(oneFile);
Console.WriteLine(logEntries);
}
Console.ReadLine();
}
}
My program does not write any log in the console, any one can explain why ?
Maybe I am all wrong. I just don't get it.
Hello I want migration unity project version from 5.0.2 to 2020.x.x
when did directly migration to 2020.x.x I did run into a problem with expection
"InvalidCastException: Object must implement IConvertible."
So I did try migration Sequentially unity5 -> V2017 -> V2018 was working well
But when I migration v2019 I did run into a problem with same expection
this code is causing problems area
[System.Serializable]
public class BookStruct
{
public int ID;
public int[] PageComposition;
public int PageCount;
public string Name;
public int CoverPageID;
public int CategoryID;
public Dictionary<SystemLanguage, TextDataTemplate> dicTextData;
public int[] RecommendBookList;
public int MarketingMark;
public string RecommendAge;
public int Priority;
public bool FreeAtNow;
}
/* public static string BinaryStringFormatter(object target)
{
MemoryStream ms = new MemoryStream();
BinaryFormatter formatter = new BinaryFormatter();
formatter.Serialize(ms, target);
return BitConverter.ToString(ms.ToArray()); // not here!
} */
public static object BinaryDeserialize(byte[] data)
{
MemoryStream ms = new MemoryStream(data);
BinaryFormatter formatter = new BinaryFormatter();
return formatter.Deserialize(ms); //here!
}
bottom code is before code
switch (Application.platform)
{
case RuntimePlatform.Android:
filepath = Application.streamingAssetsPath + "/"+bookname;
break;
default:
filepath = "file://" + Application.streamingAssetsPath + "/" + bookname;
break;
}
Debug.Log("파일 경로 확인 => " + filepath);
using (WWW www = new WWW(filepath))
{
while (!www.isDone)
{
yield return true;
}
TextAsset t = www.assetBundle.mainAsset as TextAsset;
book = (BookStruct)BK_Function.BinaryDeserialize(t.bytes);
www.assetBundle.Unload(true);
iBook.iPageCount = book.PageComposition.Length;
Debug.Log(book.dicTextData[SystemLanguage.Korean].Description);
Debug.Log("pagecount : " + book.PageCount + " // pageComposition.Length : " + book.PageComposition.Length);
}
Also,I did Debug.log file path and result is
" file://C:/unitySource/singlebook/Assets/StreamingAssets/B12_2_Cat.unity3d"
and Bookstruct is
""
Please help me (:
This is my logging.cs, It usually may create the "Log-Folder" and the Datetime.csv into the users Desktop
public static class Logging
{
public static string _Path = $"C:\\Users\\{Environment.UserName}\\Desktop\\Logs\\{DateTime.Now.ToString("dd.MM.yyyy")}.csv";
static StreamWriter _File = new StreamWriter(_Path);
public static void getPath(string path)
{
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
}
public static void logging(string message)
{
_File.Write(message);
}
}
In my main class, i use the method logging just to enter "Test" into the csv file
class Program
{
static void Main(string[] args)
{
Logging.getPath(Logging._Path);
Logging.logging("Test");
}
}
but when there is no "Logs-Folder", i get the exception that part of the path doesn´t exist. If i create the path manually, i get the exception, that the path already exists, so something's wrong with the If-Statement up in the Logging-class. But i don't know what the heck works wrong
Your path is a file and not a directory. You need to create the directory from your path
String Path = $"C:\\Users\\{Environment.UserName}\\Desktop\\Logs\\{DateTime.Now.ToString("dd.MM.yyyy")}.csv";
String Directory = System.IO.Path.GetDirectoryName(Path);
if (System.IO.Directory.Exists(Directory)==false) {
System.IO.Directory.CreateDirectory(Directory);
}
if (System.IO.File.Exists(Path)==false) {
System.IO.File.Create(Path);
}
Your _Path variable isn't actually a directory, but rather a filename.
You get the Directory with System.IO.Path.GetDirectoryName(_Path)
Your testing if an Directory exists but your giving the path to a File. Here's some code you could use to fix it:
public static string _Path = $"C:\\Users\\{Environment.UserName}\\Desktop\\Logs";
public static string _Filename = $"{DateTime.Now.ToString("dd.MM.yyyy")}.csv";
static StreamWriter _File = new StreamWriter(_File);
Try to take DirectoryPath and FilePath differently.
Move your StreamWriter to method scope so we can close this stream after Write content inside file.
public static class Logging
{
public static string _DirectoryPath = $"C:\\Users\\{Environment.UserName}\\Desktop\\Logs";
public static string _FileName = $"{DateTime.Now.ToString("dd.MM.yyyy")}.csv";
public static void getPath(string path)
{
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
}
public static void logging(string message)
{
StreamWriter _sw = new StreamWriter(_DirectoryPath + "\\" + _FileName);
_sw.Write(message);
_sw.Flush();
_sw.Close();
}
}
And from Program.cs.
Logging.getPath(Logging._DirectoryPath);
Logging.logging("Test");
Output:
I have the following directory:
\\192.168.255.86\Add-in\Requests\MyFolder1
If this directory exists (there is already a folder on the specified path) I need to create the following:
\\192.168.255.86\Add-in\Requests\MyFolder1 (1)
If directory still exists I need to create another directory:
\\192.168.255.86\Add-in\Requests\MyFolder1 (2)
and so on.
I did it using while-loop in the following method:
public static string CreateDirectory(string path)
{
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
return path;
}
int i = 1;
while (Directory.Exists(path + $" ({i})"))
{
i++;
}
path += $" ({i})";
Directory.CreateDirectory(path);
return path;
}
How to make it using recursion?
You don't need recursion here. All you want is create new directory with next available name (by adding number).
A slightly refactored method can looks like this:
public string NextDirectory(string path)
{
var dir = path;
int n = 1;
while (Directory.Exists(dir))
dir = $"{path} ({n++})";
Directory.CreateDirectory(dir);
return dir;
}
If you insist on using recursion, this should be nice and elegant:
public static string CreateDirectory(string path, int suffix = 0)
{
string directoryPath = DirectoryPath(path, suffix);
if (!CreateDirectory(directoryPath))
return CreateDirectory(path, i + 1);
return directoryPath;
}
private static bool CreateDirectory(string path)
{
if (Directory.Exists(path))
return false;
Directory.CreateDirectory(path);
return true;
}
private static string DirectoryPath(string path, int suffix)
{
return $"{path}{(suffix > 0 ? $" ({suffix})" : string.Empty)}";
}
But if you already have 'MyFolder1 (214)' your call stack might be immense!
Maybe this is a slightly neater way to do the while loop (but essentially the same):
public static string CreateDirectory(string path)
{
string createPath = GetUniquePath(path);
Directory.CreateDirectory(createPath);
return createPath;
}
private static string GetUniquePath(string path)
{
string result = path;
int i = 1;
while (Directory.Exists(result))
result = $"{path} ({i++})";
return result;
}
You can use this:
public static string CreateDirectory(string path, int i)
{
if (i>0)
{
if (Directory.Exists(path + $" ({i})"))
return CreateDirectory(path,++i);
else
{
Directory.CreateDirectory(path + $" ({i})"));
return path + $" ({i})";
}
}
else
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
return path;
}
else
return CreateDirectory(path,1);
}
Easiest way that I can add a title row to each of these files. I can't put it in the Log()'s because it would add the title row each time I reference the test.Log()'s
I thought about referencing 3 new int fields and each time I reference a Log1/2/3() it checks the value of the int and if it's 1 then add the title column else don't.I did one below but it seems redundant I figured there must be a better way.
public class Test
{
public static string File1 = DateTime.Now.ToString("yyyy-MM-dd") + "test1.csv";
public static int a = 0;
public static string File2 = DateTime.Now.ToString("yyyy-MM-dd") + "test2.csv";
public static string File3 = DateTime.Now.ToString("yyyy-MM-dd") + "test3.csv";
private static object _lockObj = new Object();
public static void Log1(string error, string record)
{ a++;
if(a==1){
lock (_lockObj)
{
File.AppendAllText(test.File1, "ERROR" + Environment.NewLine)
File.AppendAllText(test.File1, error + "," + record + Environment.NewLine);
}
}
else{
File.AppendAllText(test.File1, error + "," + record + Environment.NewLine);
}
}
public static void Log2(string message)
{
lock (_lockObj)
{
File.AppendAllText(test.File2, message + Environment.NewLine);
}
}
public static void Log3(Test c)
{
lock (_lockObj)
{
File.AppendAllText(test.File3, c + Environment.NewLine);
}
}
}
You may create a class like this:-
public class HeaderOnceAppender : RollingFileAppender
{
protected override void WriteHeader()
{
if (LockingModel.AcquireLock().Length == 0)
{
base.WriteHeader();
}
}
If you want put a Title row at the top of the file when creating it...
if(!System.IO.File.Exists(test.File1)) //if the file doesn't exist
{ //insert your header at the top
File.AppendAllText(test.File1,"My Header Line")
}
This will only append once when the file is first created