There is the following code:
public AttachedFile SaveAttachment(NewAttachment attachment) { var tmpFile = Path.GetTempFileName(); try { using (var f = File.Open(tmpFile, FileMode.Append)) { attachment.Stream.CopyTo(f); } string filePath = string.Empty; string dst = string.Empty; do { filePath = generatePathForAttachment(); dst = Path.Combine(archiveDirectory, filePath); } while (File.Exists(Path.Combine(archiveDirectory, filePath))); Directory.CreateDirectory(Path.GetDirectoryName(dst)); var attachedFile = new AttachedFile { OriginalTitle = attachment.OriginalTitle, Path = filePath, Size = attachment.Stream.Length, AuthorId = attachment.AuthorId, Created = DateTime.Now }; File.Move(tmpFile, dst); _context.Set<AttachedFile>().Add(attachedFile); _context.SaveChanges(); return attachedFile; } catch (Exception) { throw; } }
its purpose is to save the file on the server, the code is working.
Help to modify this code to reduce the consequences of the occurrence of Exception
to a minimum, i.e. I need to be done either all or nothing.
My imagination was enough only for wrapping each problem area in try
, i.e. something like:
try { if (!Directory.Exists(Path.GetDirectoryName(dst))) Directory.CreateDirectory(Path.GetDirectoryName(dst)); } catch(Exception) { //обработка исключения } try { if (File.Exists(dst)) File.Move(dst, src); } catch(Exception) { //обработка исключения }
Well, etc., but I'm not sure about the correct approach. I would be very grateful for the advice.
Implementing the path generation method for the file
private string generatePathForAttachment(params string[] args) { var dstPath = string.Empty; var srcString = string.Empty; if(args.Length==0) { srcString = DateTime.Now.ToString(); } else { srcString = string.Concat(args.Select(x=>x)); } var hash = getHashString(srcString); dstPath = Path.Combine(hash.Substring(0, 2), hash.Substring(2, 2), hash.Substring(4)); return dstPath; } private string getHashString(string s) { string hash = string.Empty; //переводим строку в байт-массим byte[] bytes = Encoding.Unicode.GetBytes(s); //создаем объект для получения средст шифрования MD5CryptoServiceProvider CSP = new MD5CryptoServiceProvider(); //вычисляем хеш-представление в байтах byte[] byteHash = CSP.ComputeHash(bytes); //формируем одну цельную строку из массива foreach (byte b in byteHash) hash += string.Format("{0:x2}", b); return hash; }
In fact, the server is a virtual machine, only I (as a developer) and the administrator have access to the directory along the program (but he does not go there)