blob: 04ca3d44c2e3291f1935050e97fe4461ae61ef19 [file] [log] [blame]
Constantin Ziesche857c7ab2020-02-25 11:24:51 +01001/*******************************************************************************
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 Ziesche02817f12020-08-04 21:40:43 +020011using NLog;
Constantin Ziesche857c7ab2020-02-25 11:24:51 +010012using System;
Constantin Ziesche02817f12020-08-04 21:40:43 +020013using System.IO;
Constantin Ziesche857c7ab2020-02-25 11:24:51 +010014using System.Linq;
15
16namespace BaSyx.Utils.PathHandling
17{
Constantin Ziesche02817f12020-08-04 21:40:43 +020018 public static class PathExtensions
Constantin Ziesche857c7ab2020-02-25 11:24:51 +010019 {
Constantin Ziesche02817f12020-08-04 21:40:43 +020020 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 Ziesche857c7ab2020-02-25 11:24:51 +010039 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}