Constantin Ziesche | 857c7ab | 2020-02-25 11:24:51 +0100 | [diff] [blame] | 1 | /******************************************************************************* |
| 2 | * Copyright (c) 2020 Robert Bosch GmbH |
| 3 | * Author: Constantin Ziesche (constantin.ziesche@bosch.com) |
| 4 | * |
| 5 | * This program and the accompanying materials are made available under the |
| 6 | * terms of the Eclipse Public License 2.0 which is available at |
| 7 | * http://www.eclipse.org/legal/epl-2.0 |
| 8 | * |
| 9 | * SPDX-License-Identifier: EPL-2.0 |
| 10 | *******************************************************************************/ |
Constantin Ziesche | 02817f1 | 2020-08-04 21:40:43 +0200 | [diff] [blame^] | 11 | using NLog; |
Constantin Ziesche | 857c7ab | 2020-02-25 11:24:51 +0100 | [diff] [blame] | 12 | using System; |
Constantin Ziesche | 02817f1 | 2020-08-04 21:40:43 +0200 | [diff] [blame^] | 13 | using System.IO; |
Constantin Ziesche | 857c7ab | 2020-02-25 11:24:51 +0100 | [diff] [blame] | 14 | using System.Linq; |
| 15 | |
| 16 | namespace BaSyx.Utils.PathHandling |
| 17 | { |
Constantin Ziesche | 02817f1 | 2020-08-04 21:40:43 +0200 | [diff] [blame^] | 18 | public static class PathExtensions |
Constantin Ziesche | 857c7ab | 2020-02-25 11:24:51 +0100 | [diff] [blame] | 19 | { |
Constantin Ziesche | 02817f1 | 2020-08-04 21:40:43 +0200 | [diff] [blame^] | 20 | private static readonly Logger logger = LogManager.GetCurrentClassLogger(); |
| 21 | public static FileInfo ToFile(this Stream stream, string filePath) |
| 22 | { |
| 23 | try |
| 24 | { |
| 25 | using (stream) |
| 26 | { |
| 27 | using (FileStream dest = File.Open(filePath, FileMode.OpenOrCreate)) |
| 28 | stream.CopyTo(dest); |
| 29 | } |
| 30 | return new FileInfo(filePath); |
| 31 | } |
| 32 | catch (Exception e) |
| 33 | { |
| 34 | logger.Error(e, "Error writing stream to file: " + e.Message); |
| 35 | return null; |
| 36 | } |
| 37 | } |
| 38 | |
Constantin Ziesche | 857c7ab | 2020-02-25 11:24:51 +0100 | [diff] [blame] | 39 | public static Uri Append(this Uri uri, params string[] pathElements) |
| 40 | { |
| 41 | return new Uri(pathElements.Aggregate(uri.AbsoluteUri, (currentElement, pathElement) => string.Format("{0}/{1}", currentElement.TrimEnd('/'), pathElement.TrimStart('/')))); |
| 42 | } |
| 43 | |
| 44 | public static string GetFormattedEndpoint(string endpoint, string aggregateId, string entityId, string separator = "/") |
| 45 | { |
| 46 | if (endpoint[endpoint.Length - 1] == separator[0]) |
| 47 | { |
| 48 | if (!endpoint.Contains(aggregateId)) |
| 49 | endpoint += aggregateId + separator + entityId; |
| 50 | else |
| 51 | endpoint += entityId; |
| 52 | } |
| 53 | else |
| 54 | { |
| 55 | if (!endpoint.Contains(aggregateId)) |
| 56 | endpoint += separator + aggregateId + separator + entityId; |
| 57 | else |
| 58 | endpoint += separator + entityId; |
| 59 | } |
| 60 | |
| 61 | return endpoint; |
| 62 | } |
| 63 | } |
| 64 | } |